Placing jQuery Validate plugin messages in new lin

2020-08-05 11:04发布

问题:

I am using jQuery Validate.

It's all working as it should but the messages are displaying one beside the other when there are more that one.

I need the messages to display in their own line.

$("#myform").validate({

errorLabelContainer: "#messageBox",
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true,
},
password: {
required: true,
minlength: 8
},
},
messages: {
name: "Please enter your name.",
email: "Please enter a valid email address.",
password: "Please enter at least 8 password characters.",
}
});
Current display: 

Message1Message2Message3

Wanted display: 

Message1
Message2
Message3

How can I do this?

回答1:

You can add div's around the messages and style them properly.

name: "<div class='msgRow'>Please enter your name.</div>",
email: "<div class='msgRow'>Please enter a valid email address.</div>",
password: "<div class='msgRow'>Please enter at least 8 password characters.</div>",


回答2:

The accepted answer is a hack...

1) you will end up with the following invalid HTML.

<label><div>Your message</div></label>

2) you would be required to declare a custom message to over-ride every single default message.


The correct method is to use the plugin's built-in wrapper option, which changes the label into a div for each message automatically.

DEMO: http://jsfiddle.net/TSKHX/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        wrapper: 'div',
        errorLabelContainer: "#messageBox",
        // your other rules & options
    });

});


回答3:

You can simple add <br/> tag in front of error messages:

messages: {"name": {required: "<br/>Error validation message"}}