Search code examples
knockout.jsknockout-validation

Difference between validation of observableArray vs regular observable


Using knockout-validation I'm trying to apply some simple validation to an observable array that checks it has at least n items.

I have created a simple test validation rule

ko.validation.rules['minSelected'] = {
    validator: function (val, minimum) {
        var result = (val.length >= minimum);
        console.dir(result);
        return result;
    },
    message: 'This field requires at least {0} selected items.'
};

which I apply on my model

self.contacts = ko.observableArray().extend({ minSelected: 1 });

The validator function gets called and I can see the correct result of the validation with my console.dir() call but the result doesn't seem to affect the validation process.

I've also tried creating an always false validator which works perfectly on the standard observable, but doesn't work on observableArray.

ko.validation.rules['never'] = {
    validator: function (val, param) {
        return false;
    },
    message: 'I will never be valid.'
};

self.single = ko.observable().extend({ never: 'ever' });
self.multiple = ko.observableArray().extend({ never: 'ever' });

Am I missing something in regards to validation on observable arrays?


Solution

  • I worked out the issue so I'm posting the answer here incase it helps other out.

    The validation did seem to be working but wasn't showing any feedback. I used the same process as validating a computed field (adding my own span which was bound to the validation message) and eveything works now as expected.

    Here's sample markup of how I got it to work:

    <select data-bind="options: contactList, 
                       optionsText: 'text', 
                       optionsValue: 'value', 
                       selectedOptions: contacts" 
            multiple>
    </select>
    <span data-bind="validationMessage: contacts" class="validationMessage"></span>