How To Limit Username Character Length?

To limit the length of username to certain charactersyou need to add the following code to your theme’s functions.php.

Note: These codes will be wiped out after theme update. So, you need to create a child theme and add the codes there. You can check out this easy Tutorial on Creating a Child Theme.

So, after creating your Child Theme, you can add these codes in the child theme’s function.php.

Note: You can enter any number instead of 15 and the entered number will be the maximum character length.

// Username limit character length.
add_action( 'user_registration_validate_user_login', 'ur_validate_user_login_field', 10, 4 );
function ur_validate_user_login_field( $single_form_field, $data, $filter_hook, $form_id ) {
   $field_label = isset( $data->label ) ? $data->label : '';
   $username = isset( $data->value ) ? $data->value : '';
    if ( 15 < strlen( $username ) ) {
     add_filter( $filter_hook, 
     function ( $msg ) use ( $field_label ) {
       return __( $field_label . ' cannot exceed 15 characters.', 'user-registration' );
     }
     );
     }
}

After you have pasted the code, users will only be able to enter the username of defined length.

Powered by BetterDocs