WordPress at a glance

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: wp-includes/user.php WP 5.2.4

<?php
function validate_username( $username ) {
	$sanitized = sanitize_user( $username, true );
	$valid     = ( $sanitized == $username && ! empty( $sanitized ) );

	/**
	 * Filters whether the provided username is valid or not.
	 *
	 * @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

No comments
    Hello, !     Log In . Register