Behseini
Behseini

Reputation: 6330

How to enable adding special character to the password validation in regular expression

I am using this regular expression to validate password entry but this is not accepting any special character

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

with this explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

How can I add the following to the expression as well?

/[!@#$%\^&*(){}[\]<>?/|\-]/

Upvotes: 0

Views: 60

Answers (1)

Nick
Nick

Reputation: 147196

Just add another positive-lookahead group if you want to ensure that there is a special character, and then add the special characters to the matching group:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%\^&*(){}[\]<>?/|\-])[0-9a-zA-Z!@#$%\^&*(){}[\]<>?/|\-]{8,}$/

Upvotes: 1

Related Questions