user registration - Restrict partially matching usernames

admin2025-06-06  3

I've been looking and looking for a solution for my problem but i have been unable to find anything.

I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.

Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?

I've been looking and looking for a solution for my problem but i have been unable to find anything.

I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.

Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?

Share Improve this question asked Feb 23, 2017 at 14:13 Gabriel DiLaurentisGabriel DiLaurentis 235 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

There's a validate_username filter hook that is used by validate_user() which is in turn used by register_new_user().

So you can disallow usernames containing admin or other prohibited terms:

add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
    // This array can grow as large as needed.   
    $disallowed = array( 'admin', 'other_disallowed_string' );
    foreach( $disallowed as $string ) {
        // If any disallowed string is in the username,
        // mark $valid as false.
        if ( $valid && false !== strpos( $username, $string ) ) {
            $valid = false;
        }
    }
    return $valid;
}

You can add this code to your theme's functions.php file or (preferably) make it a plugin.

References

  • validate_username filter hook
  • validate_user()
  • register_new_user()
  • Writing a plugin

@pat-j beat me to it by a minute, but I'll elaborate that you can use a reg ex as well:

add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
    if($valid){
        $matches = null;
        $returnValue = preg_match('/(admin)/i', $username, $matches);
        return empty($matches) ? true : false;
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749154972a316833.html

最新回复(0)