views:

348

answers:

1

Hi,

I'm just wondering how can I display both individual error messages and summary for the jquery plugin, I actually found a similar question but it just reference 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, plugin can be found here

EDIT 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;
        }
    });
});
+1  A: 

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: \n";
                $.each(errorList, function() { summary += " * " + this.message + "\n"; });
                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.

David Fullerton
Wow thanks is there anyway I can have it display which element is having the error, for example the First Name field is having the error,the alert box would be "First Name: Please enter a valid First Name".And is it possible to have an alternate error message in the alert box?I mean if the default error is "This enter a valid First Name", in the alertbox it would say "Please include atleast 1 character"
mastah
also how do you access errorList?
mastah
nevermind, posted the solution above
mastah