validate_username() WP 2.0.1
Checks whether a username (login) is valid.
Valid characters are: Latin characters, numbers, and symbols _ - space. *
.
Works based on: sanitize_user()
Hooks from the function
Return
true/false. Whether username given is valid.
Usage
validate_username( $username );
- $username(string) (required)
- Username.
Examples
#1 Validate the username and check if it exists in the DB.
If the username is valid and this user doesn't exist in the database, then register it.
<?php $username = $_POST['username']; $error = false; if( !validate_username( $username ) ) $error = "Invalid username!"; if ( !$error && username_exists( $username ) ) $error = "This user already exists!"; if( !$error ){ // register } ?>
Changelog
Since 2.0.1 | Introduced. |
Since 4.4.0 | Empty sanitized usernames are now considered invalid. |
Code of validate_username() validate username WP 5.6
function validate_username( $username ) {
$sanitized = sanitize_user( $username, true );
$valid = ( $sanitized == $username && ! empty( $sanitized ) );
/**
* Filters whether the provided username is valid.
*
* @since 2.0.1
*
* @param bool $valid Whether given username is valid.
* @param string $username Username to check.
*/
return apply_filters( 'validate_username', $valid, $username );
}Related Functions
From category: Other
- auth_redirect()
- count_many_users_posts()
- count_user_posts()
- count_users()
- email_exists()
- get_author_posts_url()
- get_current_user_id()
- get_editable_roles()
- get_the_author()