Search code examples
javascriptknockout.jsknockout-validation

How to know which field is invalid in knockout validation?


I have a rather big knockout model and I want to validate all nested models in it:

self.errors = ko.validation.group(self, { deep: true });

Validator found an error:

> self.errors()
["This field is required."]

I don't know which field of my huge model is invalid. How can I find out it?


Solution

  • I guess you should be looking for something like this

    // Getting errors
    var errors = ko.validation.group(this, {
        deep: true,
        observable: false
    });
    
    // New method: getting extended details
    var details = errors.getDetails();
    
    for (var i = 0; i < details.length; i++) {
        var d = details[i];
    
        /*
            Every element contains the following fields:
    
            "observable" - a reference to the target observable.
            "error" - the error message.
            "rule" - the name of the failed validation rule.
            "data" - an object that contains extension data (provided via "extend" method) for every rule. E.g. "data.required == true".
        */
    }
    

    PS: You need to add few lines in your validation file to make getDetails() work i.e which may not be there in validation script file you have .(check reference link & check code)

    Reference Here and credits to volpav it helped me long back .

    Just incase if someone looking for working sample check here