Advertisement

Using the Included Password Strength Meter Script in WordPress

by

WordPress uses a pretty nifty password strength script that is used to display whether the passwords you entered in the WordPress admin are: not the same, very weak, weak, medium or strong. Currently this script is only used when creating creating new users and when changing your password in your admin.

In this article, I will be teaching you on how to use the WordPress' password strength meter in your own forms.

The Password Strength Script

The strength meter script is undocumented at the time of this article, so using it requires a little digging into WordPress core. The actual script is located inside the WordPress at wp-admin/js/password-strength-meter.js. You can check it out to learn more about how the script works.

The first thing we need to do is to include this script by enqueuing it in our functions.php:

wp_enqueue_script( 'password-strength-meter' );

What's in the Script?

The script alone doesn't do everything for us. It just gives us these two JavaScript functions:

  • wp.passwordStrength.meter( password1, blacklist, password2 ).This one is the main function that we'll use. It analyzes two given strings, then gives out the strength of these two as a number from 1-5, 1 being the weakest and 5 being the strongest. It also takes an array of blacklisted words which will be considered during the computation as weak words.
  • wp.passwordStrength.userInputBlacklist().This function creates an array of words that should be considered as weak words in passwords. This function compiles strings found in your site's title, tagline and URL. It also checks for certain input fields in the current page, then adds those to the list.

We can already measure the strength of passwords with just these functions above. However, there's more to it. The script doesn't give us a results that we can display. We will have to build a function of our own to do this.

Our Strength Meter Form

Let's take this <form> as a starting point in implementing the strength meter function:

<form>
 <input type="password" name="password" />
 <input type="password" name="password_retyped" />
 <span id="password-strength"></span>
 <input type="submit" disabled="disabled" value="Submit" />
</form>

We will be using the field names and ids from above in the function that we'll create.

These are the goals that we want to achieve when we're done:

  1. When a something is typed in our password fields, we check the strength of the password,
  2. We then display the strength results below the password fields similar to how WordPress does it,
  3. Finally, we enable the submit button if the password is considered strong.

Our Strength Meter Function

Let me first show you the finished jQuery function that we'll be using. I'll explain each part in detail afterwards:

function checkPasswordStrength( $pass1,
                                $pass2,
                                $strengthResult,
                                $submitButton,
                                blacklistArray ) {
        var pass1 = $pass1.val();
	var pass2 = $pass2.val();

	// Reset the form & meter
	$submitButton.attr( 'disabled', 'disabled' );
        $strengthResult.removeClass( 'short bad good strong' );

    // Extend our blacklist array with those from the inputs & site data
    blacklistArray = blacklistArray.concat( wp.passwordStrength.userInputBlacklist() )

    // Get the password strength
    var strength = wp.passwordStrength.meter( pass1, blacklistArray, pass2 );

    // Add the strength meter results
    switch ( strength ) {

        case 2:
            $strengthResult.addClass( 'bad' ).html( pwsL10n.bad );
            break;

        case 3:
            $strengthResult.addClass( 'good' ).html( pwsL10n.good );
            break;

        case 4:
            $strengthResult.addClass( 'strong' ).html( pwsL10n.strong );
            break;

        case 5:
            $strengthResult.addClass( 'short' ).html( pwsL10n.mismatch );
            break;

        default:
            $strengthResult.addClass( 'short' ).html( pwsL10n.short );

    }

	// The meter function returns a result even if pass2 is empty,
	// enable only the submit button if the password is strong and
	// both passwords are filled up
	if ( 4 === strength && '' !== pass2.trim() ) {
		$submitButton.removeAttr( 'disabled' );
	}

    return strength;
}

jQuery( document ).ready( function( $ ) {
	// Binding to trigger checkPasswordStrength
	$( 'body' ).on( 'keyup', 'input[name=password1], input[name=password2]',
		function( event ) {
			checkPasswordStrength(
				$('input[name=password]'),         // First password field
				$('input[name=password_retyped]'), // Second password field
				$('#password-strength'),           // Strength meter
				$('input[type=submit]'),           // Submit button
				['black', 'listed', 'word']        // Blacklisted words
			);
		}
	);
});

1. Arguments & Resetting the Form

I made the function take in all the objects that we will modify or need information from. I prefixed all of the jQuery objects with a $ to make it easier to identify them from the normal JavaScript objects.

var pass1 = $pass1.val();
var pass2 = $pass2.val();

// Reset the form & meter
$submitButton.attr( 'disabled', 'disabled' );
$strengthResult.removeClass( 'short bad good strong' );

These first few lines are plain and simple, we get the passwords then we reset our form. We make the form always disabled at the start so that we can just enable later, after we get a good strength score.

We're also going to add styles to our strength meter by giving it class names depending on the score of the password later, for the start of the function, we're going to clear the style of the meter.

2. The Blacklist Array

// Extend our blacklist array with those from the inputs & site data
blacklistArray = blacklistArray.concat( wp.passwordStrength.userInputBlacklist() );

The strength meter script's blacklisted words normally should be okay. But just incase you want to add more, our function can accept additional words. Both of these are merged here to be inputted to the meter function.

3. Calling the meter Function

// Get the password strength
var strength = wp.passwordStrength.meter( pass1, blacklistArray, pass2 );

Now we call the meter function to get the strength score of the password. Next we will decide what to do with the result.

4. Displaying the Meter Results

// Add the strength meter results
switch ( strength ) {

    case 2:
        $strengthResult.addClass( 'bad' ).html( pwsL10n.bad );
        break;

    case 3:
        $strengthResult.addClass( 'good' ).html( pwsL10n.good );
        break;

    case 4:
        $strengthResult.addClass( 'strong' ).html( pwsL10n.strong );
        break;

    case 5:
        $strengthResult.addClass( 'short' ).html( pwsL10n.mismatch );
        break;

    default:
        $strengthResult.addClass( 'short' ).html( pwsL10n.short );

}

Now that we have the strength score, this is the part where we display it. WordPress gives us the JavaScript object pwsL10n that holds the labels for each strength score. We display the label inside the <span> just below the password fields, we're also assigning the corresponding style class to the label.

5. Enabling the Submit Button

// The meter function returns a result even if pass2 is empty,
// enable only the submit button if the password is strong and
// both passwords are filled up
if ( 4 === strength && '' !== pass2.trim() ) {
	$submitButton.removeAttr( 'disabled' );
}

The end of the function is for enabling our submit button only if we have a strong password.

6. Triggering on Keyup

jQuery( document ).ready( function( $ ) {
	$( 'body' ).on( 'keyup', 'input[name=password1], input[name=password2]',
		function( event ) {
			checkPasswordStrength(
				$( 'input[name=password]' ),         // First password field
				$( 'input[name=password_retyped]' ), // Second password field
				$( '#password-strength' ),           // Strength meter
				$( 'input[type=submit]' ),           // Submit button
				['black', 'listed', 'word']          // Blacklisted words
			);
		}
	);
});

Lastly, we need a way to trigger when to run our password strength meter checker. We do this by binding a handler to the keyup events to the password fields.

We're done!

Changing the Strength Labels

The labels for the strength meter are loaded up by WordPress under the object pwsL10n.

To change and override these labels, you would have to localize the script after our wp_enqueue_script in functions.php:

wp_localize_script( 'password-strength-meter', 'pwsL10n', array(
	'empty' => __( 'Strength indicator' ),
	'short' => __( 'Very weak' ),
	'bad' => __( 'Weak' ),
	'good' => _x( 'Medium', 'password strength' ),
	'strong' => __( 'Strong' ),
	'mismatch' => __( 'Mismatch' )
) );
You can read more about passing localized strings to JavaScript in the article: How to Pass PHP Data and Strings to JavaScript

Conclusion

In this article, we learned how to use the password strength script that's included with WordPress. This can be used in your custom registration forms and front-end profile pages for your website members.

I hope you enjoyed this article. I highly appreciate any feedback, comments and suggestions.

Let me know if you have found a cool way to use the password strength meter. Share your thoughts below!