1

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.

2
  • 2
    Can you create a jsfiddle or jsbin ? A link to the plugin you're using would be nice too. Commented May 13, 2014 at 12:39
  • 1
    your regex param is wrong... it should be just '^\w+$' Commented May 13, 2014 at 12:41

2 Answers 2

2

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

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

Comments

1

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,}$

Regular expression visualization

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');

Debuggex Demo

3 Comments

I am actually looking for a regular expression which won't allow special characters
Can u just tell me, whats wrong here. regex: "^[0-9]{10,}$" when allowing only numbers.
@theJava, it doesn't appear there is anything wrong with that Regex, but if you're having problems, post a new question with all of the details.

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.