I’m using the jQuery validation plugin to validate my forms, and I am also using the addmethod function to create my own validation methods. This is how I set up jQuery Validator:
$(document).ready(function() {
if ($("#validation_json").length > 0) {
var validationJSON = JSON.parse(decodeURIComponent($("#validation_json").val()));
$(".form-horizontal").validate({
rules: validationJSON.rules,
messages: validationJSON.messages
});
}
});
I have and input tag with the id validation_json, and the value set to a set of rules and messages for the jQuery validator plugin; these rules and messages are output server-side with the help of a form builder. The only issue is that whenever I add my own validation method, like so:
jQuery.validator.addMethod("uniqueemail", function(email) {
return false; //just for testing
}, "This email is already in use");
jQuery validator will use this method before submitting the field to check if it is valid (in addition the the rules set above), however if one of the addMethod‘s validates to false, it will use the message for that item set above in the validate method, and not the message passed into addMethod. Does anyone know of a way that I could get it to display the message actually passed into the addMethod functions? Thanks!
UPDATE:
Here is a jsFiddle link showing the problem.
There’s a problem with how you’ve set this up…
.validate()is used to initialize the plugin once on DOM ready. You’ve put it inside a conditional statement, so the plugin is only initialized on the form if theifcondition is met. Validation will fail to initialize at all other times. Use.valid()to trigger a validation test instead of re-initializing the plugin…Basic Demo: http://jsfiddle.net/AYvmg/
The demo shows that your custom message from
addMethodis working as expected.It’s possible to then dynamically change the custom message without another call to
.validate()by using the.rules('add')method.Another Basic Demo: http://jsfiddle.net/5RnLM/
This second demo works just like the first. Then when you click the
#testbutton, the message for the rule is changed to something else. You could use this.rules('add')method to change your custom message whenever you need and from any other function.Otherwise, perhaps you can show the associated HTML and construct a jsFiddle demo to more clearly show the issue you’re having.