validate_username() WordPress Function

The validate_username() function is used to check whether a username is valid. It is used when a new user is registering on a WordPress site. This function checks the length of the username and whether it contains only alphanumeric characters. If the username is valid, it returns true. Otherwise, it returns false.

validate_username( string $username ) #

Checks whether a username is valid.


Parameters

$username

(string)(Required)Username.


Top ↑

Return

(bool) Whether username given is valid.


Top ↑

More Information

This function attempts to sanitize the username, and if it “passes”, the name is considered valid. For additional logic, you can use the ‘validate_username‘ hook.


Top ↑

Source

File: wp-includes/user.php

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


Top ↑

Changelog

Changelog
VersionDescription
4.4.0Empty sanitized usernames are now considered invalid.
2.0.1Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More