I created this custom method for managing regular expressions:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Text not valid"
);
And then I used my method:
$(function() {
$("#registerform").validate({
rules: { password: {required: true, regex: "^[a-zA-Z09]+$"} },
messages: {
password: {regex: "A password can contain only letters or digits"}
}
});
});
The problem is that, while I can overwrite the default message for standard validation methods (like required) inside the call to validate(), I can’t do it for custom methods. So, my page will display “Text not valid” instead of “A password can contain only letters or digits”. How can I do to provide a default message and to allow to overwrite it??
Just leave the message out of your custom method if you want to always set a custom message within your
.validate()options.I don’t believe this is possible. After all, it’s reasonable to assume that since one is already using their own custom method, why would they also want to over-ride it.
Your only option would be to use a message inside the custom method or set the message within your
.validate()options, but not both.