Search code examples
knockout.jsknockout-validation

Extending Knockout ViewModel with knockoutValidate results


I've played a bit with Knockout validation and now I wondering is it possible to extend Knockout so that every view model have observable with list of errors which i get from validation? In general i have

self.validationData = {
            name: ko.observable('').validateUpperEmail(),
            childName: ko.observable('').validateOther(),
            errorList: ko.observableArray([])
        };

var errors = ko.validation.group(self.validationData);

var showErrorMessages = function () {
            errors.showAllMessages(true);

            linqjs.from(errors()).distinct('$._latestValue').forEach(function(errorMessage) {
                self.validationData.errorList.push({ text: errorMessage() });
            });

        };

Question is: is there a way to populate errorList from some other place so that i can easily remove this property from every single view model and just use inherited one?


Solution

  • You can use knockouts extend feature.

    var baseModel = function() {
        var self = this;
    
        self.errorList = ko.observable('This is an example');
    }
    
    var childModel = function() { 
        var self = this;
        self.name = ko.observable('Test1');
        self.childName = ko.observable('');
        ko.utils.extend(self, new baseModel());
    
    }
    

    Here's the fiddle.