JPS
JPS

Reputation: 2760

Reg-Ex for password validation fails

Hi my password should contain,

1. minimum 8 characters
2. minimum 1 special character
3. minimum 1 number

I am using the following reg-ex,

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

But this doesn't accept the string AAAA2@AAAA which is 8 character long, has one speical character @ and has one number 2. I have very less knowledge on RegEx. Could you please tell me what is wrong with this expression?

Upvotes: 1

Views: 68

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

The reason why the string is not accepted is because you forgot the slash with d, and the regex requires the letter d to be inside the string. Fix is

^(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[!@#$%^&*? ]).*$
 ^             ^^

Use it with a i modifier. See demo

[A-z] issue is a well-known one. Also, the initial .* should be removed, or some parts of the regex won't validate correctly.

And speaking about optimizations: length checking can almost always be moved to the end:

^(?=.*\d)(?=.*[A-Z])(?=.*[!@#$%^&*? ]).{8,}$

See another demo (again, note i modifier).

Also, see Fine-Tuning: Removing One Condition:

If you must check for n conditions, your pattern only needs to include n-1 lookaheads at the most. Often, you are even able to combine several conditions into a single lookahead.

And as far as your conditions are as above (1) minimum 8 characters, 2) minimum 1 special character, 3) minimum 1 number) - there is no English letter requirement - you can even use

^(?=.*\d)(?=.*[!@#$%^&*? ]).{8,}$

Upvotes: 3

anubhava
anubhava

Reputation: 785481

You can use:

^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*? ])[!@#$%^&*? a-zA-Z\d]{8,}$

[A-z] is not correct and will match may more characters within ASCII 65-122 range like [, ], ` etc.

RegEx Demo

Upvotes: 2

Related Questions