Stas Slabko
Stas Slabko

Reputation: 516

Validating plain observableArray()

Assume my model is very simple (a list of strings), and I don't want to put typed objects into observableArray and then validate it using deep validation ko.validation.init( { grouping: { deep: true } } ).

E.g. I want all array elements (which are plain strings) to comply with minLength:3.

Why ko.observable().extend({minLength:3}) is OK, but ko.observableArray().extend({minLength:3}) doesn't work?

Is there a workaround other than putting objects (instead of plain strings) into array?

Fiddle to start with.

Upvotes: 0

Views: 388

Answers (1)

nwayve
nwayve

Reputation: 2331

Well, you can create a minLength function on the observableArray prototype like this:

ko.observableArray.fn.stringMinLength = function (minLength) {
    var self = this;// observableArray
    // Loop through array and apply logic to each element
    // Add subscriptions to the observableArray to determine what's been added (don't care about what's been removed)
    // In the subscriptions, deal with how to apply the minLength validation
    // -can't use '.extend({ minLength: minLength })' because these are plain strings, not observables
    return self;
}

And now you can do this:

var oa = ko.observableArray(["foo", "bar", "bo"]).stringMinLength(3);

The crux of your issue is how you want to apply validation to all the string elements when oa's value has mutated.

Upvotes: 1

Related Questions