Home > jQuery > jQuery Validation Plugin – Dynamically change validator message

jQuery Validation Plugin – Dynamically change validator message

25 June, 2009


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.

Advertisements
Categories: jQuery Tags:
  1. Guu
    26 June, 2009 at 1:47 pm

    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’;

  2. 26 June, 2009 at 2:35 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.

  3. Guu
    29 June, 2009 at 10:25 pm

    it worked? great! good to know 🙂

  1. 17 September, 2009 at 12:25 am
Comments are closed.
%d bloggers like this: