3

I'm using the jQueryValidation plugin. Problem: I would like to use multiple pattern rules within for one input field. E.g.:

$("form").validate({
 rules: {
    "email": {
        required: true,
        email: true
    },
    "password": {
        required: true,
        pattern: /^[A-Za-z0-9\w]{4,20}/,
        pattern: /^[\d\w\xC4\xD6\xDC\xE4\xF6\xFC\xDF]*$/
    }
 }
});

What happens: the plugin tests only the second pattern rule. E.g. entering something like "tst" works (as this fulfils the seconds pattern) although it violates the first pattern rule.

As far as I understand the logic of rules in this plugin, all rules have to return TRUE in order to validate a form.

1
  • 1
    a javascript object can't have 2 identical keys, second instance will overwrite first. You will need to add your own method for second pattern or combine both into one regex Commented Dec 29, 2013 at 19:49

1 Answer 1

6

You cannot use the same key:value pair twice since the second instance will override the first.

You have a couple of options.

  • Combine the two regex expressions into one. One method will be declared with one error message. So instead of using the pattern rule/method from the additional-methods.js file, you will create your own custom rule using the .addMethod() method.

  • Instead of combining the regex patterns, use the pattern rule once and create a new second rule using .addMethod().

See: http://jqueryvalidation.org/jQuery.validator.addMethod/


I'd create a custom method dedicated to each regex pattern and give it a semantically relevant name, something like 'email', 'phone', 'alphanumeric', 'IP', etc. (This is also the same way all the regex evaluated rules are handled internally by this plugin.)

jQuery.validator.addMethod("foo", function(value, element) {
    return this.optional(element) || /^[A-Za-z0-9\w]{4,20}/.test(value);
}, "Your entered data is not foo");

jQuery.validator.addMethod("bar", function(value, element) {
    return this.optional(element) || /^[\d\w\xC4\xD6\xDC\xE4\xF6\xFC\xDF]*$/.test(value);
}, "Your entered data is not bar");

Declared like this...

"password": {
    required: true,
    foo: true,
    bar: true
}
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.