Isetty Ravitejakumar Isetty Ravitejakumar - 3 years ago 59
Javascript Question

How to use ( ) [ ] braces to allow as special characters in password regular Expression?

Iam using the following regular expression for password field in my project.

/^(?=.*\d)(?=.*[~!@#$%^&*)(_+-:[}="`])(?=.*[a-z])(?=.*[A-Z]).{8,}$/


My requirement is to allow atleast
1 Upper case
1 Lower case
1 Number
1 Special character.

It should allow `~!@#$%^&*)(_+-:[}=" special characters. If I enter other characters it should not allow.

But it is allowing other characters like
|\
etc

I don't have much knowledge on regular expression. Please help me, where Iam going wrong.??

Thanks alot.

Answer Source

Problem is placement of an unescaped - just after + in your character class which is in the middle and acting like a range between + i.e. 0x2b and : i.e. 0x3a. All the characters in this range are allowed due to this.

You can move - to end of character class or at the start like this:

/^(?=.*\d)(?=.*[~!@#$%^&*)(_+:[}="`-])(?=.*[a-z])(?=.*[A-Z])[~!@#$%^&*)(+:[}="`\w-]{8,}$/

Also important is to change DOT (any character) in the end to allowed set of characters as I've shown above. RegEx Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download