-1

We have a requirement for validating the password format with following rules

Length of the password should be 8- 25 character

1.numbers Mandatory [0-9]

2.small case mandatory [a-z]

3.upper case mandatory [A-Z]

4.special character optional

the following regex is not working. its forcing to provide the special character

^(?=.\d)(?=.[a-z])(?=.[A-Z])[\w~@#$%^&+=`|{}:;!.?\""()[]-]{8,25}$
LukStorms
  • 28,916
  • 5
  • 31
  • 45
PVM
  • 107
  • Have you considered not using a regular expression? –  Jan 22 '18 at 10:09
  • Possible duplicate of [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation) – ctwheels Jan 23 '18 at 20:41

2 Answers2

1

If the special character be optional, then just use this:

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

Your lookaheads had problems, e.g. (?=.\d) does not assert that a number appears anywhere in the password, it asserts that the second character in the password is a number. You meant (I think) to use (?=.*\d).

So there are three lookaheads to cover your mandatory requirements, then we match 8 to 25 characters from the following character class:

[\w~@#$%^&+=`|{}:;!.?\""()\[\]-]

This matches word characters as well as the special characters you want, though special characters are not mandatory. Note that in some regex engines you would need to escape square brackets in the character class.

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I tried this, still it is asking to enter the special character as mandatory. – PVM Jan 22 '18 at 10:28
  • @PVM I added a demo which shows that special characters are not needed for a valid password. If you are seeing different behavior, then perhaps your code has some other problem. – Tim Biegeleisen Jan 22 '18 at 10:34
  • @TimBiegeleisen You could also just simplify it by not hardcoding the special characters? And use \S to not allow whitespaces. F.e. `^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d)\S{8,25}$`. – LukStorms Jan 22 '18 at 10:51
  • @LukStorms That thought crossed my mind, but perhaps the OP really only wants alphas and that particular set of symbols. – Tim Biegeleisen Jan 22 '18 at 11:09
0

Why are you after one, big, totally unreadable and in effect unmaintainable regexp expression. Switch to 4 different expressions and check them one at a time. It's easier to maintain and less error prone. It's easier to add more rules or modify existing ones.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88