How to Use Regular Expressions to Check Password Strength

phplogo.jpg

In this previous tutorial we created a simple registration form.

Websites often require a specific strength for a password. In this lesson we will use RegEx to test the password strength.

For our password strength we will specify the following requirements:

  • a minimum of 8 characters

  • at least one uppercase letter

  • at least one number (digit)

  • at least one of the following special characters !@#$%^&*-

We will start with a basic PHP file and assume that the user has already input their password which we are storing in the variable $password.

Line 2: we have stored the user password in the variable $password

Line 3: this is where we will define the pattern we need to match

Lines 4 to 8: we will test if the password is strong enough and output a message

Line 4: we need to test if the password is strong enough. At the moment we just have pseudo code. We will use a PHP function called preg_match()

The preg_match() function

Currently we just have some psuedo code on line 4. We will use the preg_match function to check if the password matches the defined pattern as follows:

Now we need to define the pattern.

Defining Delimiters

The first step is to define the delimiters, which are just forward slashes:

Defining the Start and End of the Pattern

Now we define the start and end of the pattern using ^ for the start and $ for the end:

Minimum of 8 Characters

The first condition for the password is that it must have at least 8 characters:

We have added .{8,}

The dot means any character.

{8,} means at least 8 characters and no maximum.

If we wanted to specify that the password must be exactly 8 characters then we would use .{8}

If we wanted to specify a minimum of 8 characters and a maximum of 20 characters for the password then we would use .{8,20}

Minimum of 1 Uppercase Character

Next, we need to have a minimum of 1 uppercase character:

We have added (?=.*[A-Z])

?= means look ahead through the password.

.* means look for any number of characters.

[A-Z] means look for any uppercase characters between A and Z inclusive.

Note that we have placed this part of the pattern BEFORE the minimum number check.

Minimum of 1 Number (Digit)

We have added (?=.*[0-9])

?= means look ahead through the password.

.* means look for any number of characters.

[0-9] means look for any digit between 0 and 9 inclusive.

Minimum of 1 of the Following Special Characters !@#$%^&*-

At this point you can probably guess what you need to include.

We have added (?=.*[!@#$%^&*-])

?= means look ahead through the password.

.* means look for any number of characters.

[!@#$%^&*-] means look for any of these characters.