Regular expressions are a very good tool for password validation. Multiple rules can be applied using lookahead assertions (which work using AND
logic) applied from the beginning of the string like so:
$re = '/
# Match password with 5-20 chars with letters and digits
^ # Anchor to start of string.
(?=.*?[A-Za-z]) # Assert there is at least one letter, AND
(?=.*?[0-9]) # Assert there is at least one digit, AND
(?=.{5,20}\z) # Assert the length is from 5 to 20 chars.
/x';
if (preg_match($re, $text)) {
// Good password
}
Here's the Javascript equivalent:
var re = /^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.{5,20}$)/;
if (re.test(text)) {
// Good password
}
A good article regarding password validation using regex is: Password Strength Validation with Regular Expressions. (Although his final expressions include an erroneous dot-star at the beginning - see my comment on his blog).
Also note that regex syntax does vary from language to language (but most are converging on the Perl syntax). If you really want to know regex (in the Neo: "I know Kung-Fu" sense), then there is no better way than to sit down and read: Mastering Regular Expressions (3rd Edition) By Jeffrey Friedl.
Additional: A good argument can be made that password validation should be split up into multiple tests which allows the code to give specific error messages for each type of validation error. The answer provided here is meant to demonstrate one correct way to validate multiple rules using just one regular expression.
Happy regexing!