【问题标题】:PHP - Problem on validating empty form fieldPHP - 验证空表单字段的问题
【发布时间】:2020-06-14 00:02:11
【问题描述】:

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

在服务器端,我验证了所有这些字段,但是,我正在努力验证名称字段。如果我将输入留空或以空格(单、双或更多)开始书写并点击提交,我的 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");
}

【问题讨论】:

  • div class="form-group"&gt; <。
  • if(isset($nome) &amp;&amp; trim($nome) !== "") - 你为什么要重新检查它是否已设置?
  • 你试过添加empty检查吗? PHP empty
  • if(empty(trim($var))){ ..varaible is empty.. }
  • 我重新阅读了您的代码...if(isset($nome) &amp;&amp; trim($nome) !== "") 应该检测空白吗?从该行上方的评论看来是这样,但它的作用恰恰相反。仅当名称不为空时才会满足此条件。

标签: php html forms input field


【解决方案1】:

你可以这样尝试-

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多