jQuery Validation Plugin – Dynamically change validator message
UPDATE: Please read Guu’s comment below for a far better solution to this problem!
I’ve been using the jQuery Validation Plugin and needed to change a validation message dynamically based on the user input. I had a quick search but couldn’t find an easy solution. Unfortunately the messages are not changeable after the initial construction of the validator object. I managed to get around the problem by removing the validator an then re-adding with a new message:
Create validator
$("#Enquiry").validate({
rules: {
EnquiryText: { required: true }
},
messages: {
EnquiryText: "Enquiry must contain an entry."
}
});
Dynamically change message
function setEnquiryValidationTo(message) {
$("#EnquiryText").rules("remove");
$("#EnquiryText").rules("add", {
required: true,
messages: {
required: message
}
});
}
There may be a better/easier way to do this but I couldn’t find one via Google.
Have you tried to declare the options outside?
var EnquiryValidation = {
rules: {
EnquiryText: { required: true }
},
messages: {
EnquiryText: “Enquiry must contain an entry.”
}
};
$(”#Enquiry”).validate(EnquiryValidation );
and then change the values likey this:
EnquiryValidation.messages.EnquiryText = ‘NEW MESSAGE’;
Guu
26 Jun 09 at 1:47 pm
I hadn’t tried that but I have now and it worked a treat, thanks! I didn’t know it was possible as you can probably tell I’m new to javascript/jquery. I’ll update the post and point any unfortunates like myself directly to your comment its a far better solution.
justinram
26 Jun 09 at 2:35 pm
it worked? great! good to know
Guu
29 Jun 09 at 10:25 pm
[...] — justinram @ 9:43 pm Tags: jQuery Validation Plugin This post has been moved to my new blog http://justinramel.com/2009/06/25/jquery-validation-plugin-dynamically-change-validator-message/ Possibly related posts: (automatically generated)Lost in translation? Twitter’s coded [...]
jQuery Validation Plugin – Dynamically change validator message « just in ram
17 Sep 09 at 12:25 am