检查名称是否有效

时间:2016-02-11 17:32:56

标签: php mysqli

所以我试图创建一个表单,允许那些名字像Name_Lastname注册的人一样。但它不起作用,我使用2个输入字段名称

名称: 姓氏:

然后我使用sprintf将这两者混合到Name_Lastname中,这很有效,但是当我想检查输入的名称是否包含无效字符时,检查功能是否有效,即使我的名字是正确的表明它不是。

如果用户除名字和姓氏之外的第一个名称以外,该函数应该禁止注册,并且_,例如:Joan_Mackey = Valid

joan_Mackey = invalid
joan0_Mackey = invalid
Joan92_Mackey = invalid

但它不起作用,这是代码

   if(isset($_POST['register_button']))
    {       

        $name = clear($_POST['firstname']);
        $lastname = clear($_POST['lastname']);

        $createdname = sprintf("%s_%s", $name, $lastname);

        $ime = mysqli_real_escape_string($con, $createdname);

        $email = clear($_POST['email']);
        $pass = clear($_POST['password']);
        $cpass = clear($_POST['confpassword']);


        // Proveravanje ako ima _ i tih sranja
        $query = "SELECT * FROM Igraci WHERE Ime = '$ime'";
        $stmt = mysqli_prepare($con, $query) or die(mysqli_error($con));
        mysqli_stmt_bind_param($stmt, "s", $ime);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $row = mysqli_fetch_array($result);

        if(preg_match("([A-Z]{1,1})[a-z]{2,9}+_([A-Z]{1,1})[a-z]{2,9}", $createdname))
        {
            if($row) // Ime nije registrovano kod dole
            {
                echo "Uneseno ime: '$ime' ";
            }
            else // Ime je vec registrovano, kod dole
            {
                echo "Uneseno ime: '$ime' ";
            }
        }
        else
        {
            echo "format imena nije validan.";
            exit();
        }
    }

1 个答案:

答案 0 :(得分:0)

只需更改

if(preg_match("([A-Z]{1,1})[a-z]{2,9}+_([A-Z]{1,1})[a-z]{2,9}", $createdname))

if(preg_match("^[A-Z][a-z]{2,9}_[A-Z][a-z]{2,9}$", $createdname))

这将允许使用3到9个字符的名字和具有适当大小写的3到9个字符的姓氏来构建用户名。

说明:

^ = Start at beginning of string
[A-Z] = One capital letter
[a-z]{2,9} = two to nine small letters
_ = one underscore
[A-Z] = One capital letter 
[a-z]{2,9} = two to nine small letters
$ = Match must go up to end of string