验证plain observableArray()

时间:2013-09-10 16:53:08

标签: knockout.js knockout-validation

假设我的模型非常简单(字符串列表),我不想使用深度验证observableArray将类型化对象放入ko.validation.init( { grouping: { deep: true } } )then validate it

E.g。我希望所有数组元素(纯字符串)都符合minLength:3

为什么ko.observable().extend({minLength:3})没问题,但ko.observableArray().extend({minLength:3})不起作用?

除了将对象(而不是普通字符串)放入数组之外,还有其他解决方法吗?

小提琴start with

1 个答案:

答案 0 :(得分:1)

好吧,您可以在minLength原型上创建一个observableArray函数,如下所示:

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;
}

现在你可以这样做:

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

问题的关键在于当oa的值发生变异时,您希望如何对所有字符串元素应用验证。