gpt4 book ai didi

javascript - 无法使用 Knockout 验证来验证自定义组

转载 作者:行者123 更新时间:2023-12-03 12:14:19 25 4
gpt4 key购买 nike

我不知道如何获取 Knockout Validation plugin验证 View 模型属性的自定义选择。 我可以调用 isValid() 来成功验证整个 View 模型。

我已遵循 here 中列出的文档其中涵盖了该场景,并检查了我在堆栈溢出上可以找到的所有答案。

我的代码如下所示:

function MyViewModel() {
var self = this;

self.myproperty = ko.observableArray().extend({ minLength: { message: 'You must specify at least one item.'} })
self.anotherproperty = ko.observable().extend({ required: { params: true, message: 'You must supply a value.'} });

self.IsEntireModelValid = function() {
if (!self.isValid()) {
self.errors.showAllMessages();
return false;
}
else {
return true;
}

self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors.length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}

当我调用 self.IsAnotherPropertyValidOnly() 时,errors 变量不包含错误,但是当我调用 self.IsEntireModelValid() 时,我得到了正确的响应。

有人可以指出我做错了什么吗?

最佳答案

您需要使用errors().length

self.IsAnotherPropertyValidOnly = function() {
var errors = ko.validation.group(self.anotherproperty);
if (errors().length > 0) {
errors.showAllMessages();
return false;
}
else {
return true;
}
}

http://jsfiddle.net/WY7V3/2/

关于javascript - 无法使用 Knockout 验证来验证自定义组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799186/

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