knockout.validation是一個基於knockout.js的驗證插件,通常驗證模式以下:javascript
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 }才能夠,代碼以下:java
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({ }); } }