如何使用 php 对用户名输入应用正确的验证?

How to apply proper validations for username input with php?

我正在制作一个注册表单,其中包含用户名、性别、电子邮件和密码的输入。我已经成功地向 3 添加了验证,但用户名输入面临一个问题。 我想对我的用户名输入应用验证,检查输入是否至少有 3 个字母(大写或小写),例如

我希望结果是这样的:

Input=abc
count=3
result=accept!
--------------
Input=XYZQW
count=5
result=accept!
--------------
Input=A/_B
count=2
result=Not acceptable!

但现在它将 /_( 等所有内容都算作字母

下面是我的 php 代码,我已经应用了一些验证

<?php
$username = mysqli_real_escape_string($db, $_POST['username']);
        if (empty($username)) {
            $error_class = 'input_error';
        } elseif (strlen($username) < 3) {
            $error= '<font color="red">Your user name must be atleast 3 characters</font>';
            $error_class = 'input_error';
        } elseif (strlen($username) > 15) {
            $error= '<font color="red">Your user name is too long</font>';
            $error_class = 'input_error';
        } elseif (!preg_match("/^[A-Za-z0-9_\.]+$/ ", $username)) {
            $error = '<font color="red">Your user name must be in letters with either a number, underscore or a dot</font>';
            $error_class = 'input_error';
        } else {
            $check_uname = "SELECT * FROM users WHERE username = '$username'";
            if (!$result = mysqli_query($db_var, $check_uname)) {
                exit(mysqli_error($db_var));
            }
            if (mysqli_num_rows($result) > 0) {
                $error = '<font color="red"><b>'.$username.'</b> is already in use</font>';
                $error_class = 'input_error';
            } else {
                $error_class = 'input_no_error';
            }
        }
?>

你应该 preg_replace() your username and remove any non-letter characters and use strlen() 得到长度。

这是你应该做的:

$username = "aBd_$/"; //Actually 6
$editedusername = preg_replace('/[^a-zA-Z]/m', '', $username);
$count=strlen($editedusername); //But it returns 3
echo $count;

输入值实际上是 6 个字符,包含 _$/ 但是你不需要它们所以它会 return 3 这是 aBd.

如果您对代码有任何问题,请告诉我!