Testing password strength with a simple regex

In a world where the biggest security risk exists between the chair and the keyboard, weak passwords are the quickest way of allowing yourself to be hacked. A brute force attack for a 8 character lowercase password can be done in (micro)seconds. And although you should always protect your application against these attacks ( e.g. allowing three wrong password entries before suspending the account ) I’ve always felt you should be “training” your end-users. Help them create strong passwords so that this specific part of security is the least of your worries when developing a web application.

I’ve been using the the following regular expression for my passwords for some time now.

(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$

This regular expression doesn’t set a maximum number of allowed characters but it will check if the password:

  • contains at least 1 uppercase letter
  • contains at least 1 lowercase letter
  • contains at least 1 number or special character
  • is at least 8 characters in length

Now if we’d only were able to prevent people from writing down their passwords the world would be a better place for a webdeveloper.

4 Replies to “Testing password strength with a simple regex”

  1. but this is unpractical because you need to tell the user the reason his password is weak and you don’t know where the regex failed, so you need to test each case separately

    1. True, but who does that nowadays? Just a simple text next to the field should be sufficient to alert user on how a password should look like and what it should contain.

  2. You could remove the non-capturing modifier on each of the sub patterns and inspect the matches to find out what parts of the regex failed to match.

Comments are closed.