Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

ajax - Display both summary and individual error messages using the jQuery validation plugin

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: 
";
                $.each(errorMap, function(key, value) {
               summary += key + ': ' + value + "
";
                });
                alert(summary);
                submitted = false;
            }
            this.defaultShowErrors();
        },
        invalidHandler: function(form, validator) {
            submitted = true;
        }
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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:

$(document).ready(function() {
    var submitted = false;
    ('.selector').validate({
        showErrors: function(errorMap, errorList) {
            if (submitted) {
                var summary = "You have the following errors: 
";
                $.each(errorList, function() { summary += " * " + this.message + "
"; });
                alert(summary);
                submitted = false;
            }
            this.defaultShowErrors();
        },          
        invalidHandler: function(form, validator) {
            submitted = true;
        }
    });
});

See here for a complete list of options that can be passed to the validate method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...