PHP-验证空白表格字段时出现问题

时间:2020-03-01 14:36:22

标签: php html forms input field

我有一个简单的表格,其中包含三个输入:姓名,消息和电子邮件。

在服务器端,我验证所有这些字段,但是,我在努力验证名称字段。如果我将输入留空或使用空格(单,双或更多)开始书写并点击提交,则我的php代码接受此名称为有效名称(不应使用此名称)。

有人知道如何防止这种情况发生吗?

这里是我的代码:

第1页-表单:

<form action="enviar-email.php" method="POST" name="emailform">
            <div class="form-group">
                <input type="text" class="form-control" id="name" name="nome"  placeholder="Type your name here" >
            </div>
            <div class="form-group">
                < input type="text" class="form-control" id="email" name="email" placeholder="Youre@email.com here">
            </div>
            <div class="form-group">
                 <textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="write your message" ></textarea>
            </div>

            <div class="form-group">
                 <input type="submit" name="submit" value="Send" class="btn btn btn-special" onclick="alert('Thanks!')" >

            </div>
</form>

第2页-我在其中验证字段的PHP页面。

if(isset($_POST['nome'])){ $nome = $_POST['nome']; }
if(isset($_POST['email'])){ $email = $_POST['email']; } 
if(isset($_POST['mensagem'])){ $message = $_POST['mensagem']; }

// blank fields or name that start with space are not getting caught by this if
if(isset($nome) && trim($nome) !== ""){
    Header("location:contato.php");

}
if (!preg_match("/^[a-zA-Z ]+$/",$nome)) {
    Header("location:contato.php");
}

2 个答案:

答案 0 :(得分:1)

在验证脚本中,您将发布的值分配给名为$name的变量,但if条件正在检查名为$nome的变量。当您展示代码时,这仅仅是偶然的错字吗?如果不是拼写错误,那么您的if条件将永远不会满足(它将在isset($nome)上始终失败)。

答案 1 :(得分:0)

您可以尝试这样-

if(isset($_POST['name']) && !empty($_POST['name'])){ $name = $_POST['name']; }
相关问题