I need to validate a password with the following requirements: 1. Be at least seven characters long 2. Contain at least one letter (a-z or A-Z) 3 Contain at least one number (0-9) 4 Contain at least one symbol (@, $, %, etc) Can anyone give me the correct expression?
A:
For a single regex, the most straightforward way to check all of the requirements would be with lookaheads:
/(?=.*[a-zA-Z])(?=.*\d)(?=.*[^a-zA-Z0-9\s]).{7,}/
Breaking it down:
.{7,}
- at least seven characters(?=.*[a-zA-Z])
- a letter must occur somewhere after the start of the string(?=.*\d)
- ditto 2, except a digit(?=.*[^a-zA-Z0-9\s])
- ditto 2, except something not a letter, digit, or whitespace
However, you might choose to simply utilize multiple separate regex matches to keep things even more readable - chances are you aren't validating a ton of passwords at once, so performance isn't really a huge requirement.
Amber
2010-03-08 02:49:17