【问题标题】:Stop form submission when inputs are not validated (one page PHP form and Processor)未验证输入时停止表单提交(一页 PHP 表单和处理器)
【发布时间】:2017-04-24 03:40:42
【问题描述】:

我有一个 PHP 文件,它获取数据然后使用 $_POST 方法显示它。我知道如何使用 PHP 验证表单的输入:

if($data = "") {
echo "This Field Is Required";
}

但我不知道如何避免表单提交数据。我是否在这个 if 语句中添加一个新行?我在这篇文章中看到了与 header:locations 相关的内容 - Stop Submit With Empty Input Values Using PHP,但我认为这对我不起作用,因为我的表单和处理器位于一个文件中。我相信这很简单,但是在浏览网页时很难找到任何答案。感谢您的帮助:)

【问题讨论】:

    标签: php html validation form-submit requiredfieldvalidator


    【解决方案1】:

    这是一个前端(客户端验证),您还需要在 PHP(服务器端)验证表单。但是使用 html5 和 js 可以阻止表单提交,如果它没有经过验证。

    对于 php,您需要在服务器端进行验证。如果无效,则不保存到数据库,也不应重定向用户。返回一些错误消息,要求提供更多数据/必填字段。

    示例:

    $error = [];
    
    if ($offer['year'] < 2014) {
        $error['year'] = 'must be later than 2014';
    }
    ...
    
    if (count($error)) {
       echo "your error msg here"
    } else {
       $db->insert('formtable', $form);
    }
    

    $(document).ready(function() {
      // loader (after submit)
      $('button[type="submit"]').click(function(e) {
        let formValidity = $('#myform')[0].checkValidity();
        if (formValidity) {
          console.log('Submitted yep!');
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <form id="myform">
      <input type="text" value="" required>
      <button type="submit" value="submit">SUBMIT</button>
    </form>
    <div id="other">
      Trigger the handler
    </div>

    【讨论】:

      【解决方案2】:

      这是使用 php 验证表单的简单示例。

      PHP:

      $con = mysqli_connect("localhost","root","","db");
      
      if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
      
      if (isset($_POST['submit'])) {
      
          if (isset($_POST['submit'])) {
              $fn = mysqli_real_escape_string($con,$_POST['fn']);
              $ln = mysqli_real_escape_string($con,$_POST['ln']);
              $tnc = mysqli_real_escape_string($con,$_POST['tnc']);
      
              // validation
              if (!empty($fn && $ln)) {
                  if ($tnc == 1) {
                      echo "Succeed.!";
                  }else{
                      echo "You must Accept Out T&C.!";
                  }
              }else{
                  echo "Please fill the required field.!";
              }
          }
      }
      

      HTML:

      <form action="" method="post">
          <input type="text" name="fn" />
          <input type="text" name="ln" />
          <input type="checkbox" name="tnc" value="1" >Accept T&C.</input>
          <input type="submit" name="submit" />
      </form>
      

      这可能正是您想要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多