How to validate password strength using a regular expression
Regular expressions are as complicated as they are powerful.
Source: Matt Mombrea
Password strength requirements are a hot topic as of late due to a slew of compromised sites and services exposing millions of user accounts to hackers. To no one’s surprise, the most used passwords are embarrassingly weak. “password” anyone?
The first step in a long process of securing any service with user accounts is enforcing a password policy of sufficient complexity. This can be done in a number of ways programmatically by creating the proper logic during the registration process, but that solution is specific to each scenario. A more general solution is to use RegEx (regular expressions) to define a pattern that meets your desired requirements.
Regular expressions are as complicated as they are powerful. They can be very intimidating in the beginning, so the best way to start is to take an example and tweak it until you produce exactly what you need. It also helps to list out your goals before you begin.
For this example, the rules I would like to enforce are:
The password length must be greater than or equal to 8
The password must contain one or more uppercase characters
The password must contain one or more lowercase characters
The password must contain one or more numeric values
The password must contain one or more special characters
Those are a lot of requirements. Amazingly, all of those requirements can be expressed in a single line of a regular expression:
Granted, that single line RegEx looks like a random garble of characters at first glance. In reality, it is a carefully constructed set of rules to dictate a pattern match on a string. As a primer, have a look at the RegEx syntax guide, then load up a RegEx tester like Rubular and start playing around with different combinations until you get a feel for it.
Once you have your expression written, implementing it in the programming language of your choice is trivial as RegEx is well supported in nearly every language.