使用 jQuery 验证插件显示摘要和单个错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2848765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display both summary and individual error messages using the jQuery validation plugin
提问by chriz
How can I display both individual error messages and summary for the jQuery plugin?
如何显示 jQuery 插件的单个错误消息和摘要?
I actually found a similar question , but it just references some hooks I can use, but I'm not sure where to start.
我实际上发现了一个类似的问题,但它只是引用了一些我可以使用的钩子,但我不确定从哪里开始。
I got the displaying individual error messages part, but I need to display the summary in an alert box on submit, and plugin can be found here.
我得到了显示个别错误消息的部分,但我需要在提交时在警告框中显示摘要,插件可以在这里找到。
Just found out how, thanks for David's code, and on my follow-up question - The alert box would be "First Name: Please enter a valid First Name".
刚刚发现如何,感谢大卫的代码,以及我的后续问题 - 警报框将是“名字:请输入有效的名字”。
Code below:
代码如下:
$(document).ready(function() {
var submitted = false;
('.selector').validate({
showErrors: function(errorMap, errorList) {
if (submitted) {
var summary = "You have the following errors: \n";
$.each(errorMap, function(key, value) {
summary += key + ': ' + value + "\n";
});
alert(summary);
submitted = false;
}
this.defaultShowErrors();
},
invalidHandler: function(form, validator) {
submitted = true;
}
});
});
回答by David Fullerton
As the linked question says, the showErrors
callback is called whenever errors are shown. You can use this to create your summary and alert it. You can then call this.defaultShowErrors()
to display the normal individual error messages.
正如链接的问题所说,showErrors
只要显示错误,就会调用回调。您可以使用它来创建您的摘要并提醒它。然后您可以调用this.defaultShowErrors()
以显示正常的单个错误消息。
By default showErrors is called for a lot of events (submit, keyup, blur, etc). You could either disable those, or use the invalidHandler
method which is only called when an invalid form is submitted.
默认情况下,showErrors 会为许多事件(提交、键控、模糊等)调用。您可以禁用它们,也可以使用invalidHandler
仅在提交无效表单时调用的方法。
Example:
例子:
$(document).ready(function() {
var submitted = false;
('.selector').validate({
showErrors: function(errorMap, errorList) {
if (submitted) {
var summary = "You have the following errors: \n";
$.each(errorList, function() { summary += " * " + this.message + "\n"; });
alert(summary);
submitted = false;
}
this.defaultShowErrors();
},
invalidHandler: function(form, validator) {
submitted = true;
}
});
});
See herefor a complete list of options that can be passed to the validate
method.
有关可以传递给该方法的选项的完整列表,请参见此处validate
。