A thread on House of Fusion’s CF-Talk about Regular Expressions consumed me for a few hours yesterday. Someone asked an innocent question about creating a pattern to ensure that a string of characters between 6 and 12 characters in length would contain at least one number. He didn’t specify, but I assumed this was for a password field.

I ended up with at least 5 versions of my final solution that I was sure were right – until I tested them. Sometimes I didn’t even test them correctly and posted an invalid pattern to the list. I finally went to one of my favorite sites, Regular-Expressions.info and had to re-read the lookahead section a few times. Then after a few false starts I was finally able to develop something that works.

This will ensure that a password has only alphanumeric characters and no whitespace.

^(?=.*[A-Za-z])(?=.*[0-9])(?!.*[^A-Za-z0-9])(?!.*\s).{6,12}$

This pattern will allow any non-whitespace character passwords

^(?=.*[A-Za-z])(?=.*[0-9])(?!.*\s).{6,12}$

If you want to get really crazy, you can start enforcing strong passwords where at least one character must be lower case alpha and one must be upper case.

^(?=.*[A-Za-z])(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?!.*[^A-Za-z0-9])(?!.*\s).{6,12}$