Search Knowledge Base by Keyword

How to enforce strong password policies during user registration?

You are here:

During a user registration process on a WordPress website, the user registering on your website does not have a WordPress user role assigned yet.

In this article we explain how you can enforce strong password security policies during the user registration process, since WPassword is able to validate passwords of users which do not have a user role yet.

Which password policies apply to users without a role?

When configuring password policies with the WPassword plugin you start by configuring the generic policies that apply to all the users on the website. If you require different policies for users with specific user roles you can configure different password policies for users with that WordPress user role.

The generic password policies configured in the All tab also apply to users who do not have a user role, for example users registering on your website.

Implementing password validation during user registration

We will be illustrating this with an example; we will be using the User Registration plugin to showcase how to validate passwords in a user registration custom form. Of course, this is just an example and the process can be adapted to other plugins.

Here is the code in full. We will examine and explain it further below:

add_action( 'user_registration_validate_user_pass','wpassword_validate_text_field',10,4);

function wpassword_validate_text_field($single_form_field, $data, $filter_hook, $form_id) {
$field_label = isset( $data->label ) ? $data->label : '';
$value = isset( $data->value ) ? $data->value : '';

$ppm = ppm_wp();
$pwd_check = new PPM_WP_Password_Check();
$does_violate_rules = $pwd_check->does_violate_rules( $value, true );
$issues_found = '';

if ( $does_violate_rules ) {
$error_strings = $ppm->msgs->error_strings;
foreach ( $does_violate_rules as $violation => $value ) {
$issues_found .= $error_strings[ $violation ] .'
';
}
}

if( $does_violate_rules ) {
add_filter( $filter_hook, function ( $msg ) use ( $issues_found ) {
return __( $issues_found, 'user-registration' );
});
}
}

Code explanation

The main logic is executed in the wpassword_validate_text_field() function. First we take the new password that has been submitted through the form and check if its violates any of the configured policies using the following:

$pwd_check->does_violate_rules( $value, true );

If the password the user submitted does not meet the configured policies, the code creates an error string which is returned to the user, explaining in detail the reasons why the password was not accepted. An example of this is illustrated in the below screenshot:

User is prompted with details if the password does not meet the configured policies