Search code examples
knockout.jsknockout-validation

Validate input value, if it's wrong than set default


I'm trying to write a validation of my input field value. If the value is wrong then I want to set a default value. Unfortunately it's checking it, set the default value and later is set the wrong value. I'm trying to use the extender validation. Before I tried with the "subscribe" But Again without success. Here is my example about scenario

On start in input I have 0.56 I'm changing it to 0.95 . So the extender is checking that the 0.95 is grosser than 0.85 and is changing the value to 0.85. Unfortunately in my case is still 0.95. I add some alert after- target(0.85) I can see that value is changing to 0.85 but after that is again 0.95.

Any idea what I'm doing wrong?

Here is my code

ko.extenders.checkInput = function (target) {

    var result = ko.computed({
        read: target,
        write: function (newValue) {

            if (newValue > 0.85) {
                target(0.85);
            } 

         });

    //return the new computed observable
    result(target());

    return result;


};

self.inputValue = ko.observable(0.56).extend({ checkInput: '' });

Solution

  • You need to use notifySubscribers if the value doesn't change and extend the computed to always notify about a change (as per knockout documentation on extenders):

    ko.extenders.checkInput = function(target, option) {
        var result = ko.computed({
            read: target,
            write: function(newValue) {
                var current = target(),
                valueToWrite = Math.min(newValue, 0.85);
                if (valueToWrite !== current) {
                    target(valueToWrite);
                } else {
                    if (newValue !== current) {
                        target.notifySubscribers(valueToWrite);
                    }
                }
            }
        }).extend({ notify: 'always' });
        result(target());
    
        return result;
    };
    

    http://jsfiddle.net/w017dc50/