Search code examples
knockout.jsknockout-validation

Counting knockout validation error messages in a public function


I have a jsFiddle here:

There is an array in knockout viewmodel and every array element raises an error. Is there a way to count number of error messages for the whole view model and access it by a public javascript function?

The idea here is to count total errors of the viewmodel and then perform some action outside in a javascript public function.

Thanks


Solution

  • Try out this modified version of your fiddle: http://jsfiddle.net/js8hh/4/

            self.Errors = ko.computed(function() {
                var errs = [];
                for(var p in self) {
                    if(self.hasOwnProperty(p)) {
                        var pObj = self[p];
                        if(!!!ko.validation.utils.isValidatable(self[p])) {
                            console.info("ope, nvm");
                        } else {                            
                            if(!ko.validation.validateObservable(pObj)) {
                                errs.push({'Property':p,'Error':ko.utils.unwrapObservable(pObj.error)});
                            }
                        }
                    } else {
                        console.trace("skipping prototype property");
                    }
                }
                return errs;
            });
    

    and then at the bottom

                addJointHolder: addJointHolder,
                AllErrors: ko.computed(function() {
                    result = []
                    ko.utils.arrayForEach(jointholders(),function(jh) {
                        if(jh.Errors().length > 0) {
                            result.push({'JointHolder':jh,'Errors':jh.Errors()});
                        }
                    });
                    return result;
                })