【发布时间】:2013-05-29 20:44:43
【问题描述】:
我使用 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)
有什么想法吗?
谢谢。
【问题讨论】:
标签: knockout.js knockout-validation