Question

I have the following javascript code

function AppViewModel(){
    this.myValue = ko.observable().extend({ minNumber: "5"}).extend({ maxNumber: "20" });
}

ko.extenders.minNumber = function(target, minValue){
    target.hasError = ko.observable();
    target.errorMessage = ko.observable();

    function validate(newValue){
        target.hasError(parseInt(newValue) < parseInt(minValue) ? true : false);
        target.errorMessage(parseInt(newValue) < parseInt(minValue) ? "MinVal" : "");
    }

    validate(target());

    target.subscribe(validate);

    return target;
};

ko.extenders.maxNumber = function(target, maxValue){
    target.hasError = ko.observable();
    target.errorMessage = ko.observable();

    function validate(newValue){
        target.hasError(parseInt(newValue) > parseInt(maxValue) ? true : false);
        target.hasError(parseInt(newValue) > parseInt(maxValue) ? "MaxVal" : "");
    }

    validate(target());

    target.subscribe(validate);

    return target;
};

ko.applyBindings(new AppViewModel());

and the following HTML

<input data-bind="value: myValue, valueUpdate: 'afterkeydown'"/><br/>
<span data-bind="text: myValue"></span>
<span data-bind="text: myValue.errorMessage"></span>
<span data-bind="text: myValue.hasError"></span>

What I am trying to achieve is a validation on an observable with a minimum and maximum integer value. My code works http://jsfiddle.net/Gazzo100uk/nCtpx/5/ but I am unsure as to why it works for instance why does the maxNumber not clear the errorMessage property in its validate function even if the integer is less than 5 in this example or vice versa for the min.

What order will these functions be fired?

Like I say, it does what I want it to do but I don't understand how it is working and to be honest I never expected it to work.

Can anybody shed any light please?

Regards, Gary

No correct solution

OTHER TIPS

I think that the main issue that was causing it to "work" is that you were not setting errorMessage in the maxNumber extender, so it was not being cleared inappropriately:

function validate(newValue){
    target.hasError(parseInt(newValue) > parseInt(maxValue) ? true : false);
    target.hasError(parseInt(newValue) > parseInt(maxValue) ? "MaxVal" : "");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top