# Username Rules for New Registrations

> Requires new usernames to be a sensible length, use only letters, numbers, dots, dashes and underscores, and not be just a number.

- Type: PHP
- Runs: Run everywhere
- Category: [Users](https://wpide.com/library/category/users/)
- Tags: registration, usernames, validation
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/username-rules-on-registration/

## Code

```php
$wpide_username_min = 4;
$wpide_username_max = 30;

add_filter( 'registration_errors', function ( $errors, $login ) use ( $wpide_username_min, $wpide_username_max ) {
    $length = strlen( $login );

    if ( $length < $wpide_username_min || $length > $wpide_username_max ) {
        $errors->add( 'wpide_username_length', sprintf( '<strong>Error:</strong> Usernames must be between %d and %d characters.', $wpide_username_min, $wpide_username_max ) );
    }

    if ( ! preg_match( '/^[A-Za-z0-9._-]+$/', $login ) ) {
        $errors->add( 'wpide_username_chars', '<strong>Error:</strong> Usernames may only use letters, numbers, dots, dashes and underscores.' );
    } elseif ( ctype_digit( $login ) ) {
        $errors->add( 'wpide_username_digits', '<strong>Error:</strong> Usernames cannot be only numbers.' );
    }

    return $errors;
}, 10, 2 );
```

## Notes

Existing usernames are not affected. Adjust the length limits at the top.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Username Rules for New Registrations" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
