Param-Ganak
Param-Ganak

Reputation: 5875

Regular expression is required to add a custom validation method in jquery

I want to do validation of a password field on a login form. The requirement for the password is that the password should be combination of alphabet and numbers. I write a new validation function to fulfil above requirement and added it to jQuery using validator.addmethod(). The function code is as follows

$.validator.addMethod('alphanum', function (value) {
    return /^[a-zA-Z 0-9]+$/.test(value);
}, 'Password should be Alphanumeric.');

Problem is this function is not working properly i.e. it accepts alphabetic password (like abcdeSD) and numerical password (like 4255345) and dot give error message for such inputs.

  1. so is there anything wrong in my code?
  2. is the written regular expression is wrong and if yes then what will be the correct reg expression?

Upvotes: 0

Views: 1829

Answers (3)

Dhanasekaran
Dhanasekaran

Reputation: 3

Use this expression for password for javascript:

/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%_!]).{8,8})/

You can add the any special characters in the expression.

Manually add the characters for in [@#$%_!] inside.

Upvotes: 0

Anurag
Anurag

Reputation: 141879

Password must contain only alphabets and digits

/^[a-zA-Z0-9]+$/

It must contain alphabet(s)

/[a-zA-Z]+/

It must contain digit(s)

/[0-9]+/

And'ing these

/^[a-zA-Z0-9]+$/.test(value) && /[a-zA-Z]+/.test(value) && /[0-9]+/.test(value)

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838216

Use negative lookaheads to disallow what you don't want:

^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z 0-9]+$

Upvotes: 2

Related Questions