knockout.validation 验证数组里的元素
knockout.validation是一个基于knockout.js的验证插件,一般验证模式如下:
var viewModel = function (Data) { var self = this; self.OtherMoney = ko.observable().extend({ required: true, pattern: { params: /^\d+[\.]?\d{0,2}$/g, message: "必须是数字,并且最多两位小数!" } }); self.PaymentList = ko.observableArray(); $.each(Data, function (n, value) { self.PaymentList.push({ Id: ko.observable(value.Id), NowClaimAmount: ko.observable(0), }) }) //保存 self.Save = function () { self.errors = ko.validation.group(self); if (self.errors().length > 0) return; $.ajax({ }); } }
但是如果我们要验证 self.PaymentList数组里的元素时, self.errors = ko.validation.group(self)这个是获取不到数组里面的错误信息的,这时候需要加{deep: true }才可以,代码如下:
var viewModel = function (Data) { var self = this; self.OtherMoney = ko.observable().extend({ required: false, pattern: { params: /^\d+[\.]?\d{0,2}$/g, message: "必须是数字,并且最多两位小数!" } }); self.PaymentList = ko.observableArray(); $.each(Data, function (n, value) { self.PaymentList.push({ Id: ko.observable(value.Id), NowClaimAmount: ko.observable(0).extend({ required: true, pattern: { params: /^\d+[\.]?\d{0,2}$/g, message: "必须是数字,并且最多两位小数!" } }), }) }) //保存 self.Save = function () { self.errors = ko.validation.group(self, { deep: true }); if (self.errors().length > 0) return; $.ajax({ }); } }