Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation plugin - Custom message

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?

like image 805
Detonator Avatar asked Jul 21 '11 14:07

Detonator


4 Answers

$("#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"              }     }); 
like image 121
Shef Avatar answered Oct 03 '22 11:10

Shef


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.", }); 
like image 33
user828267 Avatar answered Oct 03 '22 11:10

user828267


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." />
like image 38
detale Avatar answered Oct 03 '22 12:10

detale


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"
);
like image 35
Bill Keller Avatar answered Oct 03 '22 12:10

Bill Keller