0

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.

Community
  • 1
  • 1
Stas Slabko
  • 506
  • 5
  • 14

1 Answers1

1

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.

nwayve
  • 2,291
  • 23
  • 33
  • oh that's too much for a simple extension of validation rules to members of observableArray... I'd better use artificial objects for my array which i can easily extend: `ko.observableArray([{value: ko.observable("foo").extend({minLength:3})}, ..., ...])` – Stas Slabko Sep 13 '13 at 06:46
  • Yeah, I would probably go with this as well. You might look at the mapping plugin to map these objects in the array for you. Or just create a simple constructor function that you pass in a string and an int that returns an object with a `value` property that's an observable, whose minLength is set to the int you pass. `ko.observableArray([new Item('foo', 3), new Item('bar', 3), new Item('bo', 3), etc... ])`. It's a blessing and a curse that there are a lot of ways to do the same thing. – nwayve Sep 13 '13 at 09:00