I am new to JQuery and am using the JQuery validation plugin.
I would like to ask, how to override the default messages to display also text in label associated with form element.
I would get message something like this:
Field Password is required. instead of default This field is required.
Field PostCode must contain at least 3 characters. instead of default Please enter at least 3 characters.
I need to override the default behaviour of this plugin, because I do not want to specify custom message for each item for every type of validation.
Is it possible?
$("#signupform")
.validate({
rules: {
password: "required",
postcode: {
required: true,
minlength: 3
}
},
messages: {
password: "Field Password is required",
postcode: {
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
});
This is what I found when I was looking for the same thing a couple of days ago. Unfortunately I can't remember where I found it, so I can't give the person who wrote the answer credit.
jQuery.extend(jQuery.validator.messages, {
required:"This field is required.",
equalTo:"Password fields do not match.",
email:"Please enter a valid email.",
});
There's a more concise way to achieve this.
Use "data-msg" or "data-msg-(rulename)" to override default error message for a predefined rule or a custom rule. (after jQuery validation v1.11.0, currently v1.16.0)
<input id="pwd" name="pwd" type="password" value=""
required
data-msg-required="Field Password is required." />
<input id="postcode" name="postcode" type="text" value=""
required
data-msg-required="Field PostCode is required."
minlength="3"
data-msg-minlength="Field PostCode must contain at least 3 characters." />
I needed to do the same thing, and ended up creating a custom method so that its message could be shared across multiple forms.
I found this answer in a similar Stack Overflow question: How can we specify rules for jquery validation plugin by class?
$.validator.addMethod(
"newEmail", //name of a virtual validator
$.validator.methods.email, //use the actual email validator
"Custom error message"
);
add this after the plugin:
jQuery.extend(jQuery.validator.messages, {
required: "Your new default message",
email: "That's not a valid email"
});
you can put it in a separate file if you want, but make sure it's included after the plugin itself