Reputation: 15034
Below is my regular expression
method.
$.validator.addMethod("regex", function (element, value, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
}, "Special Characters not permitted");
Below is my rules
.
var rules = {
cname: {
required: true,
minlength: 8
//alphanumeric:true
//regex: "/^\w+$/i"
//uniqueCompnameName: true
}
}
When i pass the regular expression to regex, it does not work at all.
Upvotes: 1
Views: 54
Reputation: 67898
So keep in mind that \w
is going to be the same as [a-zA-Z0-9_]
. Now, for the Regex, you are really looking for this here:
^[A-Za-z0-9]{8,}$
That's saying any word character with a minimum length of 8 characters.
And then finally, when passing the Regex into the function, you want to pass it like this:
regex: '^[A-Za-z0-9]{8,}$'
and then when building the RegExp
you want to pass the flags as the second parameter:
var re = new RegExp(regexp, 'i');
Upvotes: 1
Reputation: 388316
Try to pass the regex using a regex notation instead as a string
$.validator.addMethod("regexp", function (value, element, regexp) {
if (typeof regexp == 'string') {
regexp = new RegExp(regexp);
}
return this.optional(element) || regexp.test(value);
}, "Special Characters not permitted");
then
name1: {
required: true,
regexp: '/^\w+$/'
},
name2: {
required: true,
regexp: /^\w+$/i
}
Demo: Fiddle
Upvotes: 2