Regular expression to check password strength


The requirement was to enforce a strong password which consists of

at least one number or space, and one upper case letter.

 

So as usual, I googled the regular expression and looked up a few regular expression books. To divide and conquer this requirement,

  1. at least one number: .*[0-9]
  2. space: .*\s, \s means any spatial character like space and tab
  3. one upper case: .*[A-Z]

Also, you need to use positive look ahead so that any character follows, satisfying all those requirements

My first regular expression I came up with was

(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]|.*\s).*

This did work in .Net, but not in javascript. I used ASP.Net regular expression validator, and the tricky point was the same expression was processed by different engine. When it is validated on the service side, .Net process the expression. On client-side validation, javascript engie evaluate the expression. So the same password worked on firefox with server validation, but errored on IE which does client-side validation. I googled a bit and found a similar expression by Douglas Karr 

var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");

So, using it, I changed my expression and it worked both on client-side and on server side like a charm!

The final version:

(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]|.*\s).*