Jquery.Validate error message on top of form with

2020-06-06 07:45发布

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

enter image description here

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条回答
Luminary・发光体
2楼-- · 2020-06-06 08:01

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/

查看更多
登录 后发表回答