使用 jQuery 验证插件显示摘要和单独的错误消息
如何显示 jQuery 插件的单独错误消息和摘要?
我实际上发现了一个类似的问题,但它只是参考了一些我可以使用的钩子,但我不知道从哪里开始。
我得到了显示单独的错误消息部分,但我需要在提交时在警报框中显示摘要,并且可以找到插件 这里。
刚刚找到了方法,感谢大卫的代码,以及我的后续问题 - 警报框将是“名字:请输入有效的名字”。
代码如下:
$(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;
}
});
});
How can I display both individual error messages and summary for the jQuery plugin?
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;
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如链接的问题所述,每当显示错误时都会调用
showErrors
回调。您可以使用它来创建摘要并发出警报。然后,您可以调用this.defaultShowErrors()
来显示正常的各个错误消息。默认情况下,许多事件(提交、keyup、模糊等)都会调用 showErrors。您可以禁用这些功能,或者使用
invalidHandler
方法,该方法仅在提交无效表单时调用。示例:
有关可传递给 此处 的选项的完整列表,请参阅代码>验证方法。
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 callthis.defaultShowErrors()
to display the normal individual error messages.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.Example:
See here for a complete list of options that can be passed to the
validate
method.