Search code examples
knockout.jsknockout-validation

Knockout-validation corrected errors


I am using KnockoutJS and Knockout-Validation. I am using the property errorElementClass, however, I'd like to be able to have another class assigned to the elements when the validation errors are corrected. This class would only be assigned to the elements after the element has encountered an error and has been corrected.

Has anyone attempted this sort of thing?


Solution

  • You could add an extender to the observable and subscribe to changes to the isValid property

    Like this

    ko.extenders.corrected = function(observable) {
        observable.isCorrected = ko.observable();
        observable.isValid.subscribe(function(value) {
            observable.isCorrected(value == true);
        });
    
        return observable;
    };
    

    http://jsfiddle.net/fkkJz/

    You need to manually bind the css

    <input data-bind="value: field, css: { corrected: field.isCorrected }"  />
    

    You could also do a little hack so that you do not need to manually bind css. This will override the value binding and check if it should inject a css binding http://jsfiddle.net/HuLWD/

    UPDATE: I needed this functionally my self due to a requirement and remembered this answer, but I also needed it to clear the corrected state if a second correct value was submitted, it can be achived like

    ko.extenders.corrected = function(observable) { 
        var state = observable();
        observable.isCorrected = ko.observable();
        observable.isValid.subscribe(function(value) {
            observable.isCorrected(value == true);
            state = observable();
        });
    
        observable.subscribe(function(value) {
            if(state !== value) {
                observable.isCorrected(false);
            }
        });
    
        return observable;
    };
    

    http://jsfiddle.net/HuLWD/1/