Password validation
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 leas开发者_StackOverflowt one number (0-9) 4 Contain at least one symbol (@, $, %, etc) Can anyone give me the correct expression?
/.{7,}/
/[a-zA-Z]/
/[0-9]/
/[-!@#$%^
...]/
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.
精彩评论