您在一个正则表达式中要求很多,这可能是可能的,但这不是最好的方法,您想让用户知道为什么他们的用户名出错。
function checkUsername($username) {
$username = trim($username);
if (empty($username)) {
return "username was left blank.";
}elseif (strlen($username) < 4) {
return "username was too short";
}elseif (strlen($username) > 26) {
return "username was too long";
}elseif (!preg_match('~^[a-z]{2}~i', $username)) {
return "username must start with two letters";
}elseif (preg_match('~[^a-z0-9_.]+~i', $username)) {
return "username contains invalid characters.";
}elseif (substr_count($username, ".") > 1) {
return "username may only contain one or less periods.";
}elseif (substr_count($username, "_") > 1) {
return "username may only contain one or less underscores.";
}
return true;
}
然后要检查你会做的:
$validUsername = checkUsername($username);
if ($validusername !== true) {
echo "An error occured: " . $validUsername;
}
这样,用户就知道存在错误,并且可以更轻松地修复它,而不是对错误是什么视而不见。此外,您应该停止使用已折旧的ereg,preg_match。
注意使用 !== 进行检查,这也检查类型,因为它可以返回一个字符串(通过松散的比较将返回 true)。只是一个FYI。