gpt4 book ai didi

knockout.js - ko.validation with validatedObservable 给我奇怪的结果

转载 作者:行者123 更新时间:2023-12-01 10:00:30 24 4
gpt4 key购买 nike

我使用 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() 在用户未输入任何邮政编码或姓名时始终返回 true。我注意到 validationModel().postcode.isValid() 是假的,因此将 validationModel.isValid() 设置为 True 是不合逻辑的。

现在,对于我的新实现,我必须测试两件事:(!validationModel.isValid() || validationModel().errors().length>0)

有什么想法吗?

谢谢。

最佳答案

尝试在您的 viewModel 中覆盖您的 isValid() 函数:

self.isValid = ko.computed(function () {
return ko.validation.group(
self,
{
observable: true,
deep: true
}).showAllMessages(true);
}, self);

关于knockout.js - ko.validation with validatedObservable 给我奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com