0

I need to validate password with: At least one uppercase, at least one lowercase, at least one number OR symbol, at least 8 characters.

I have this regex:

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

This works fine except of > it checks string on number AND symbol, but not on number OR symbol. And also character length 8-20, not at least 8 but gives range. I want it to check number OR symbol. Any ideas? Thanks and have a good day!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
KoboldMines
  • 428
  • 2
  • 6
  • 21

1 Answers1

1

The (?=.*\d) positive lookahead requires a digit in the string AND (?=.*[^a-zA-Z0-9]) requires a char other than ASCII letter or digit.

To make the regex require a digit OR a char other than ASCII letter or digit, merge the two lookaheads as

(?=.*[^A-Za-z])

Basically, you need to remove 0-9 from the second lookahead and it will require any char but an ASCII letter.

Result:

/^(?=.*[^A-Za-z])(?=.*[a-z])(?=.*[A-Z]).{8,20}$/

Or, a much more efficient version based on the contrast principle:

/^(?=[A-Za-z]*[^A-Za-z])(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{8,20}$/

See the regex demo.

If a space is not special, add it to the lookahead:

/^(?=[A-Za-z ]*[^A-Za-z ])(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{8,20}$/
            ^          ^
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563