Wednesday, February 26, 2014

Regular Expressions for password validation

Regular Expressions can look like Greek and be a real pain to wrap your head around, but sometimes they are necessary.  It's fairly easy to find a regular expression for common uses like email and phone numbers.  However, I didn't have much luck finding a regular expression to validate the format of a password.  This is probably because there are so many variations on what is considered an acceptable password.

By reverse engineering some Microsoft examples, I've discovered an easy way to create a regular expression for your specific password validation needs.

Let's walk through this:

What is the minimum length of the password?  Let's say 8.  So start with:

(?=.{8,})

Do you require at least one number?  If yes, then append:

(?=(.*\d){1,})

Do you require at least one capital letter?  If yes, then append:

(?=(.*[A-Z]){1,})

Do you require at least one lower case letter?  If yes, then append:

(?=(.*[a-z]){1,})

Do you require at least one "special" character?  If yes, then append:

(?=(.*\W){1,})

When we string these requirements together, we get:

(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*\W){1,})

By omitting and including the various sections, you should be able to create a regular expression that matches your application's definition of an "acceptable" password.

No comments:

Post a Comment