daddywoodland daddywoodland - 22 days ago 7
jQuery Question

How to add messages to a class with addClassRules

I'm using jQuery Validate to validate a page with a large number of repeated rows of data. Due to limited space, each row has it's own validation summary.

I use addClassRules to apply the validation rules to the page but the default error messages are too generic in the summary (e.g. "Field is required, Field is required etc).

Example:

jQuery.validator.addClassRules({
amount: {
required: true,
range: [0, 2000000]
},
comment: {
maxlength: 51
},
owner: {
notFirstOption: true
},
A: {
required: function (element) {
return getParentElement($(element), "tr").find(".colB input.B").val().length > 0;
},
digits: true
}});


Can you apply custom messages for the rules in each validation class? Ideally I'm after something like:

jQuery.validator.addClassMessages({
amount: {
required: "Amount is required",
range: "Amount must be between 0 and 2,000,000"
},
comment: {
maxlength: "Comment may be a maximum of 51 characters"
},
owner: {
notFirstOption: "Please select an owner"
},
A: {
required: "A is required if B is entered",
digits: "A must be numeric"
}});


Thanks in advance for any help you can offer!

Answer

In the documentation, the answer is to alias the method that you want to call and add the custom message.

Check the reference under the "Refactoring rules" heading:

// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required,
"Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength, 
// leverage parameter replacement for minlength, {0} gets replaced with 2
$.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
Comments