函数文档

validate_username()

💡 云策文档标注

概述

validate_username() 函数用于检查用户名是否有效,通过调用 sanitize_user() 进行清理并比较结果。开发者可利用 'validate_username' Hook 添加自定义验证逻辑。

关键要点

  • 参数:$username(字符串,必需),表示待检查的用户名
  • 返回值:布尔值,指示用户名是否有效
  • 核心逻辑:使用 sanitize_user() 清理用户名,若清理后与原始用户名一致且非空,则视为有效
  • Hook:提供 'validate_username' 过滤器,允许开发者修改验证结果
  • 相关函数:sanitize_user() 用于清理用户名,apply_filters() 用于调用过滤器
  • 变更记录:从 4.4.0 版本起,清理后为空用户名被视为无效

代码示例

if ( ! empty( $_POST['username'] ) && validate_username( $_POST['username'] ) ) {
    // Go ahead and save the user...
}

📄 原文内容

Checks whether a username is valid.

Parameters

$usernamestringrequired
Username.

Return

bool Whether username given is valid.

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.

Source

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

Hooks

apply_filters( ‘validate_username’, bool $valid, string $username )

Filters whether the provided username is valid.

Changelog

Version Description
4.4.0 Empty sanitized usernames are now considered invalid.
2.0.1 Introduced.

User Contributed Notes