views:

37

answers:

2

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?

+3  A: 
  1. /.{7,}/
  2. /[a-zA-Z]/
  3. /[0-9]/
  4. /[-!@#$%^...]/
Ignacio Vazquez-Abrams
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:

  1. .{7,} - at least seven characters
  2. (?=.*[a-zA-Z]) - a letter must occur somewhere after the start of the string
  3. (?=.*\d) - ditto 2, except a digit
  4. (?=.*[^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