validate_username()WP 2.0.1

Checks whether a username (login) is valid.

Valid characters are: Latin characters, numbers, and symbols _ - space. *.

Hooks from the function

Return

true|false. Whether username given is valid.

Usage

validate_username( $username );
$username(string) (required)
Username.

Examples

0

#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 6.6.2

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