validate_username()WP 2.0.1

Checks the correctness of the username (username - login).

If the username contains invalid characters, the function will return false — check failed.

Allowed characters: a-z _ - space . @, i.e., Latin alphabet, digits, and _ - space . @.

Suitable for checking the login, but not the displayed name! Since the underlying function is sanitize_user() with the second parameter true, i.e., strict sanitization. For example, all Cyrillic characters will be removed.

Hooks from the function

Returns

bool. true if the name meets the standards, otherwise false.

Usage

if( ! validate_username( $username ) ){
	// incorrect login
}
$username(string) (required)
Username (login) to check.

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.

validate_username() code WP 7.1

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