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*.

Related posts

1 comment

  1. 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 );
    }
    

Comments are closed.