1

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??

1
  • Not really sure what you're asking. Why can't you just leave the message "text not valid" out of your custom method? Commented Nov 27, 2012 at 1:50

1 Answer 1

1

Just leave the message out of your custom method if you want to always set a custom message within your .validate() options.

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    }
);

How can I do to provide a default message and to allow to overwrite it?

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.