如何验证数组? [英] How to validate an array?
问题描述
我正在尝试使用敲除验证库来验证对象数组.对于我来说,如何为一组可观察对象组成一个验证组并不是一件容易的事.我设法使其正常工作的唯一方法是这样的(包含JSFIDDLE ):
I am trying to use knockout validation lib to validate an array of objects. It is not straightforward to me how to form a validation group for an array of observables. The only way I managed to make it work is like this (JSFIDDLE included):
var Note = function () {
var self = this;
self.name = ko.observable().extend({ required: true });
};
var viewModel = function() {
var self = this;
self.notes = ko.observableArray([new Note(), new Note()]);
self.validatedObservables = function() {
var arr = [];
ko.utils.arrayForEach(self.notes(), function(note) {
arr.push(note.name);
});
return arr;
};
self.errors = ko.validation.group(self.validatedObservables());
self.submit = function () {
if (self.errors().length != 0) {
self.errors.showAllMessages();
}
};
};
ko.applyBindings(new viewModel());
看来我的方法过于冗长.根据源代码,您可以简单地将一个可观察对象传递给ko.validation.group:
It seems like my approach is unnecessarily verbose. According to the source code you can simply pass an observable to ko.validation.group:
self.errors = ko.validation.group(self.notes());
但这是行不通的.
推荐答案
有一个用于深度分组(递归)的配置选项.
可以使用ko.validation.init( { grouping: { deep: true } } )
进行全局设置
或group
调用本身,例如:self.errors = ko.validation.group( self.notes(), {deep: true} );
There is a configuration option for the grouping to be deep (recursive).
It can be set either globally with ko.validation.init( { grouping: { deep: true } } )
or in the group
call itself, e.g.: self.errors = ko.validation.group( self.notes(), {deep: true} );
此处更新了小提琴: http://jsfiddle.net/KHFn8/4116/
顺便说一句,您可以用更短的形式编写它:
BTW, the way you did it could be written in much shorter form:
self.errors = ko.validation.group(
ko.utils.arrayMap(self.notes(), function(note) { return note.name }));
修改: 我的小提琴不再适用于最新版本的KO验证.这是在我给出答案时(2012年6月)使用最新版本的相同小提琴: http://jsfiddle .net/KHFn8/4117/
Edit: My fiddle no longer works with the latest version of KO validation. Here is the same fiddle using the latest version at the time I gave the answer (June 2012): http://jsfiddle.net/KHFn8/4117/
这篇关于如何验证数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!