Mohanraj S K
Mohanraj S K

Reputation: 657

Regular expression to allow either number or special characters

I have a regex to allow characters, atleast one number and special character text limit 8 to 15..

function validatePassword(password) {
    var re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@.$!%*#?&])[A-Za-z\d$@.$!%*#?&]{8,15}$/i;
    return re.test(password);
}

Now I need to change this regex to accept either one number or one special character and same 8 to 15 limit

Upvotes: 3

Views: 2747

Answers (2)

Tamas Rev
Tamas Rev

Reputation: 7174

All you need is to unify the digits and the special character lookaheads:

function validatePassword(password) {
    var re = /^(?=.*[A-Za-z])(?=.*[$@.$!%*#?&0-9])[A-Za-z\d$@.$!%*#?&]{8,15}$/i;
    return re.test(password);
}

Explanation:

  • digits can be specified as [0-9] or as \d too.
  • I chose the character class specification so they fit into the special character char class.
  • A lookahead is something like (?=...)

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You need to remove the lookahead requiring a digit, and move the \d to the lookahead requiring a special character:

var re = /^(?=.*[A-Za-z])(?=.*[\d$@.!%*#?&])[A-Za-z\d$@.!%*#?&]{8,15}$/;
                               ^^

If you do not need to require at least one letter, remove (?=.*[A-Za-z]).

Details:

  • ^ - start of string
  • (?=.*[A-Za-z]) - there must be at least 1 ASCII letter
  • (?=.*[\d$@.$!%*#?&]) - there must be at least 1 digit, or any one of the special chars in the class
  • [A-Za-z\d$@.!%*#?&]{8,15} - the string should only consist of letters, digits, and the special chars listed, from 8 to 15 occurrences.
  • $ - end of string.

Note that once you are using a-zA-Z, you do not need the /i case insensitive modifier.

Also, no ned to repeat $ in one and the same character class.

Upvotes: 5

Related Questions