Jquery.Validate error message on top of form with

2020-06-06 07:53发布

问题:

Is it possible to display the error message above the form like this with jQuery Validation Plugin?

I'm doing something like this, but it shows how many fields are invalid. I'm new with jQuery validation and learing so I don't have any idea about this.

$("#addQ").validate({
    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
            $("#error-message").show().text("You missed " + errors + " field(s)");
        } else {
            $("#error-message").hide();
        }
    }
});

Thanks.

回答1:

You would use showErrors instead of the invalidHandler to do something like this...

showErrors: function(errorMap, errorList) {
    var messages = '';
    $.each( errorList, function( i, val ) {
        messages = messages + "<li>" + errorList[i].message + "</li>";
    });
    $("#summary").html(messages);
}

OR with field names:

showErrors: function(errorMap, errorList) {
    var messages = '';
    $.each( errorMap, function( key, value ) {
        messages = messages + "<li>" + key + ": " + value + "</li>";
    });
    $("#summary").html(messages);
}

http://jsfiddle.net/hauv7y0a/