我使用ko.validation来检查页面上的有效数据,如下所示:
var postcode = ko.observable(),
name = ko.observable();
var validationModel = ko.validatedObservable({
postcode: postcode.extend({ required: true }),
name: name.extend({ required: true })
});
然后在我的确定按钮中,我在提交前检查验证:
var buttonOk = function () {
if (!validationModel.isValid()) {
validationModel.errors.showAllMessages();
return false;
}
...
它工作得很好:如果用户没有输入邮政编码和名称,则验证失败。
现在我添加了更多的验证规则:
postcodeMustNotAlreadyExists + denominationMustNotAlreadyExists 像这样:
var validationModel = ko.validatedObservable({
postcode: postcode.extend({ required: true }),
name: name.extend({ required: true })
}).extend({
postcodeMustNotAlreadyExists: cities,
denominationMustNotAlreadyExists: cities
});
ko.validation.rules['postcodeMustNotAlreadyExists'] = {
validator: function (val, cities) {
// Try to find a match between the typed postcode and the postcode in the list of cities
var match = ko.utils.arrayFirst(cities(), function (item) {
return (val.postcode() === item.postCode());
});
return !match;
},
message: 'This postcode already exists!'
};
ko.validation.rules['denominationMustNotAlreadyExists'] = {
validator: function (val, cities) {
// Try to find a match between the typed denomination and the denomination in the list of cities
var match = ko.utils.arrayFirst(cities(), function (item) {
return (val.name() === item.name());
});
return !match;
},
message: 'This denomination already exists!'
};
ko.validation.registerExtenders();
现在validationModel.isValid()
,当用户没有为邮政编码或姓名输入任何内容时,返回始终为真。而且我注意到这validationModel().postcode.isValid()
是错误的,因此将validationModel.isValid() 设置为True 不是逻辑。
现在有了我的新实现,我必须测试两件事:(!validationModel.isValid() || validationModel().errors().length>0)
任何想法?
谢谢。