使用preg_match在PHP中进行表单验证

时间:2014-08-31 08:51:36

标签: php validation

您好我正在尝试验证一个简单的HTML表单。这是我的HTML代码 -

<HTML>
    <body>
        <form method="get" action="password.php">
        User ID<input type="text" name="user" id="user" required/><br/>
        Password<input type="password" name="pass" id="pass" required/><br/>
        <input type="submit" value"Login Here">
        </form>
    </body>
    </html>

密码必须仅包含数字。我的密码.php是 -

<?php
    $name=$_GET['user'];
    $pass=$_GET['pass'];

    $strlen1= strlen($name);
    $strlen2= strlen($pass);

    $regex= "/^[789][0-9]{9}$/";   // my password should contain digits only.

    if($strlen1==0 | $strlen2==0)   
        {
            echo 'Username or password field is empty'.'<br/>';
        }

    else if($name==$pass)
        {
            echo 'Go for a better password'.'<br/>';
        }

    else if(!preg_match($regex,$pass))
        {
            echo 'password is invalid'.'<br/>';
        }

    else
        {
            echo 'You have successfully logged in'.'<br/>';
        }

    ?>

在我输入有效密码时运行脚本,例如 - &#34; 123456&#34;消息说 - &#34;密码无效&#34;。 请让我知道上面代码中的错误。 谢谢!!!

1 个答案:

答案 0 :(得分:1)

您的密码应以7,8,9中的任何一个开头,后跟9位

$regex= "/^[789][0-9]{9}$/";

过滤数字只能将其替换为:

$regex="/^\d+$/";