gpt4 book ai didi

javascript - knockout validation - 如何显示单个错误消息

转载 作者:数据小太阳 更新时间:2023-10-29 03:51:19 25 4
gpt4 key购买 nike

我在提交验证时检查我的 View 模型 as described here on SO, actually .

除了“提交”操作之外,我的表单还有一个“保存进度”操作。它以几乎相同的方式提交给服务器,但必填字段更少。

我想将四个绝对必填字段保留在它们当前在 View 模型中的位置...即将它们保留在较大的验证组中以供提交。

在 Knockout Validation 中是否有一种方法可以像 showAllMessages() 一样简单地显示特定消息,以显示完整的验证组?我查看了源代码,但找不到任何像 showMessage() 附加到单个错误的内容。

或者,有没有办法从我的 View 模型中挑选字段并将它们放入自己的验证组中(但也将它们保留在更大的组中)?

举个例子:

var ViewModel = ko.validatedObservable({
requiredForSave1: ko.observable().extend({ required: true }),
requiredForSave2: ko.observable().extend({ required: true }),
requiredForSubmit: ko.observable().extend({ required: true })
// ... and many more.
});

$('#sumbit').on('click', function(){

//check the entire validation group
if ( ViewModel.errors().length === 0 ){
doSubmit();
}
else{
ViewModel.errors.showAllMessages();
}
});

$('#save').on('click', function(){

//check only part of the validation group
if ( ViewModel.requiredForSave1.isValid() &&
ViewModel.requiredForSave2.isValid() ){

doSubmit();
}
else{
//show only one or two specific validation messages.
//???
}

});

有没有办法填充最后一个 else block ,或者我应该对此采取不同的方法?

谢谢

最佳答案

Or, is there a way to pick and choose fields from my View Model and put them in their own validation group (but keep them in the larger group as well)?

是的,您可以根据需要定义任意多个组;和 observables 可以在多个验证组中。

因此,例如,假设您的 View 模型中所有错误的验证组如下:

ViewModel.errors = ko.validation.group(ViewModel);

您还可以像这样添加单独的组:

ViewModel.saveErrors = ko.validation.group([ViewModel.requiredForSave1, ViewModel.requiredForSave2]);

此外,通过在验证组上调用 showAllMessages,您只会显示该组内可观察对象的消息。 ViewModel.saveErrors.showAllMessages() 将仅显示 requiredForSave1requiredForSave2

的验证消息

希望对你有帮助

关于javascript - knockout validation - 如何显示单个错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21265472/

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