I'm using the jQueryValidation plugin. Problem : I would like to use multiple pattern rules within for one input field. Eg:
$("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. Eg 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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.