Filter username field on registration for profanity and unwanted words

How do I add a filter to the username field to stop new users from registering using unwanted words such as administrator or general profanity?

Ideally, if I could add a large list of words that are blocked with the option to add asterisk (*) as a wildcard like genitals*.

Solutions Collecting From Web of "Filter username field on registration for profanity and unwanted words"

There are two very different hooks you can use, depending on the installation:

  • wpmu_validate_user_signup for multi-site and
  • registration_errors for single-site.

The following untested code shows how to use them. You can tweak the array in user_name_is_forbidden() to your needs. Use regular expressions for the matches.

// multi-site
add_filter( 'wpmu_validate_user_signup', function( $result )
{
    // there is already an error
    if ( $result['errors']->get_error_message('user_name') )
        return $result;

    if ( user_name_is_forbidden( $result['user_name'] ) )
        $result['errors']->add('user_name',  __( 'That username is not allowed.' ) );

    return $result;
});

//single-site
add_filter( 'registration_errors', function( $errors, $name )
{
    if ( user_name_is_forbidden( $name ) )
        $errors->add('user_name',  __( 'That username is not allowed.' ) );
    return $errors;
}, 10, 2);


function user_name_is_forbidden( $name )
{
    // If you need the character '~', write it as '\~'.
    $forbidden = array(
        'admin.*',
        'genitals.*',
        'system.*'
    );

    return (bool) preg_match( '~' . join( '|', $forbidden ) . '~i', $name );
}