1

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?

JPS
  • 2,730
  • 5
  • 32
  • 54

2 Answers2

3

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,}$
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Hmm this will match `AAAA2@[]AA` as well, not clear from question whether this is fine or not since `[` and `]` are not in the provided character class. – anubhava Aug 28 '15 at 11:44
2

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1.this expression fails for `aaaaaaaaaa1!` , `ABCabc1!` or any string without character `d`. 2. the user can enter only small letters without capital letters in my requirement but this expression mandates the string to have both one small and capital letters – JPS Aug 28 '15 at 11:03
  • 1
    It was actually a copy/paste error from question. `d` should have been `\d` for digit. See updated one now. – anubhava Aug 28 '15 at 11:06