【问题标题】:I would like to know how to stop form submission when the validation fails?我想知道验证失败时如何停止表单提交?
【发布时间】:2013-09-24 04:53:30
【问题描述】:

我是 php 新手,这是我的代码。

当任何字段为空时,我想停止表单提交...

<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

   if (empty($_POST["name"]))
     {$nameErr = "Name is required";}
   else if (empty($_POST["email"]))
     {$emailErr = "Email is required";}
   else if (empty($_POST["website"]))
     {$website = "";}
   else if (empty($_POST["comment"]))
     {$comment = "";}
   else if (empty($_POST["gender"]))
     {$genderErr = "Gender is required";}

}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="welcome.php"> 
   <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   <label>Comment:</label> <input type="text" name="comment">
   <br><br>
   <label>Gender:</label>
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <span class="error">* <?php echo $genderErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>
</body>
</html>

【问题讨论】:

    标签: php forms validation


    【解决方案1】:

    如果你想打印所有的错误,那么你的代码应该如下...

    <?php session_start(); error_reporting(0);?>
    <!DOCTYPE HTML> 
    <html>
    <head>
    <style>
    .error {color: #FF0000;}
    </style>
    </head>
    <body> 
    <?php
    
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
       if (empty($_POST["name"]))
         {$_SESSION['name']= "Name is required";}
       if (empty($_POST["email"]))
         {$_SESSION['email'] = "Email is required";}
       if (empty($_POST["website"]))
         {$_SESSION['website'] = "Website is required";}
       if (empty($_POST["comment"]))
         {$_SESSION['comment'] = "comment is required";}
       if (empty($_POST["gender"]))
         {$_SESSION['gender'] = "Gender is required";}
    }
    if($_POST['name']!="" && $_POST['email']!="" && $_POST['website']!="" && 
    
    $_POST['gender']!="")
    {
        header("Location: welcome.php");
    }
    ?>
    
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field.</span></p>
    <form method="post" action=""> 
       <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
       <br><br>
       <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
       <br><br>
       <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
       <br><br>
       <label>Comment:</label> <input type="text" name="comment">
       <br><br>
       <label>Gender:</label>
       <input type="radio" name="gender" value="female">Female
       <input type="radio" name="gender" value="male">Male
       <span class="error">* <?php echo $_SESSION['gender'];?></span>
       <br><br>
       <input type="submit" name="submit" value="Submit"> 
    </form>
    </body>
    </html>
    <?php 
        unset($_SESSION['name']);
        unset($_SESSION['email']);
        unset($_SESSION['website']);
        unset($_SESSION['comment']);
        unset($_SESSION['gender']);
    ?>
    

    如果您想访问欢迎页面中的所有变量。只需如下代码

    home.php

    <?php session_start(); error_reporting(0);?>
    <!DOCTYPE HTML> 
    <html>
    <head>
    <style>
    .error {color: #FF0000;}
    </style>
    </head>
    <body> 
    
    
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field.</span></p>
    <form method="post" action="welcome.php"> 
       <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
       <br><br>
       <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
       <br><br>
       <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
       <br><br>
       <label>Comment:</label> <input type="text" name="comment">
       <br><br>
       <label>Gender:</label>
       <input type="radio" name="gender" value="female">Female
       <input type="radio" name="gender" value="male">Male
       <span class="error">* <?php echo $_SESSION['gender'];?></span>
       <br><br>
       <input type="submit" name="submit" value="Submit"> 
    </form>
    </body>
    </html>
    <?php 
        unset($_SESSION['name']);
        unset($_SESSION['email']);
        unset($_SESSION['website']);
        unset($_SESSION['comment']);
        unset($_SESSION['gender']);
    ?>
    

    welcome.php

    <?php
    session_start();
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
       if (empty($_POST["name"]))
         {$_SESSION['name']= "Name is required";}
       if (empty($_POST["email"]))
         {$_SESSION['email'] = "Email is required";}
       if (empty($_POST["website"]))
         {$_SESSION['website'] = "Website is required";}
       if (empty($_POST["comment"]))
         {$_SESSION['comment'] = "comment is required";}
       if (empty($_POST["gender"]))
         {$_SESSION['gender'] = "Gender is required";}
    
    }
    if(empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["website"]) || empty($_POST["gender"]))
    {
        header("Location: home.php");
    }
    
    echo $_POST['name'];
    ?>
    

    【讨论】:

    • 我想在这个页面本身显示错误并阻止它导航到“welcome.php”???
    • 是的,错误会显示在页面本身,试试这个方法。最后不要忘记unset所有会话变量。
    • 到底是什么意思?因为我对 php 真的很陌生
    • 我只是粘贴了你的整个代码......如果我点击提交按钮,所有 d 字段为空,页面将移动到welcome.php..
    • 我觉得@shashank 过于懒惰,希望人们只是为他们做他们的工作......他们的询问的答案很明确。这篇文章对我的目的最有帮助,谢谢 Sumit :)...仅供参考...这可能应该被接受为答案。
    【解决方案2】:

    如果你想在提交之前验证你的数据,你应该使用 javascript 更具体地说 jquery 来验证数据客户端本身,

    给表单一个这样的 id

    method="post" action="welcome.php" id="form1"

    所有表单元素的 ID

    $('#form1').submit(function() { your validation rules here if($('#email').val().length == 0) return false; else return true; });

    return false 停止提交。

    如果你打算做前端而不仅仅是 php,那么你真的应该尝试一下 jquery 会让你的生活更轻松

    【讨论】:

    • 我不想借助 js 或 jquery 的帮助,我只是想知道它在 php 中是否可行。
    • 然后在最后添加一个else并在那里添加你的提交代码
    【解决方案3】:

    Javascript 是客户端,PHP 是服务器端,所以在没有按下提交按钮“将数据发布到服务器”之前,您可以使用 php 验证表单。检查字段执行不同的操作,如数据库插入、计算等,您不能将响应发送回客户并告诉他您这里的伙伴遇到了这个错误,我不会使用这种数据。好吧,您可以使用 ajax 在服务器端实时验证表单。最好的方法是验证客户端,然后在您使用来自客户端的所有数据之前,因为每个人都在撒谎,您会再次检查服务器。这是example.

    【讨论】:

      【解决方案4】:

      听起来您想在 PHP 中进行验证,但停止向 PHP 提交数据。那是不可能的。如果您想在 PHP 中进行验证,无论如何都会提交所有数据。如果需要,您可以使用exit() 停止 PHP 执行。否则,您需要使用 JavaScript 验证表单客户端(您可以在此处或通过 Google 找到大量信息)。

      【讨论】:

        【解决方案5】:

        如果任何字段为空,我您需要的表单不会被提交为什么不试试这个..

        <label>Name:</label> <input type="text" name="name" required> <span class="error">* <?php echo $nameErr;?></span>
           <br><br>
            <label>E-mail:</label> <input type="text" name="email" required> <span class="error">* <?php echo $emailErr;?></span>
               <br><br>
               <label>Website:</label> <input type="text" name="website" required> <span class="error"><?php echo $websiteErr;?></span>
               <br><br>
               <label>Comment:</label> <input type="text" name="comment" required>
               <br><br>
               <label>Gender:</label>
               <input type="radio" name="gender" value="female" required>Female
               <input type="radio" name="gender" value="male" required>Male
        

        【讨论】:

        • 我不想接受 pf html5 的帮助,我知道使用 js 或 jquery 执行此操作的其他各种方法,我只是想知道它是否可以在 php 中使用 ..
        【解决方案6】:

        这是对 PDO 数据库使用 PHP 的另一种方法:

        • 在您完成所有必填字段之前,它不会提交到您的数据库,并且还会显示所需的输入错误消息。
        • 如果您忘记填写其中一个必填字段并提交,则不会清除所有字段。

        我在连接中添加了一个 If 语句。

        <?php
         // define variables and set to empty values
           $nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
           $name = $email = $city = $comment = $gender = "";
        
          if ($_SERVER["REQUEST_METHOD"] == "POST") {
           if (empty($_POST["name"])) {
             $nameErr = "Please add a name";
          } else {
              $name = validateInput($_POST["name"]);
              // check if name only contains letters and whitespace
              if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white 
              space allowed";} 
            }
        
          if (empty($_POST["email"])) {
            $emailErr = "Please add an email";
          } else {
             $email = validateInput($_POST["email"]);
             // check if email is an email format
              if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
                $emailErr = "Invalid email format";
              }
            }
        
         if (empty($_POST["city"])) {
            $cityErr = "Please add your city";
          } else {
            $city = validateInput($_POST["city"]);
            // check if city only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
                $cityErr = "Only letters and white space allowed";
            }
          }
        
          if (empty($_POST["comment"])) {
            $commentErr = "Please add your comment";
          } else {
            $comment = validateInput($_POST["comment"]);
               // check if comment only contains letters and whitespace
               if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
                $commentErr = 'Only "/", "-", "+", and numbers';  
            }
          }
        
          if (empty($_POST["gender"])) {
            $genderErr = "Please pick your gender";
          } else {
            $gender = validateInput($_POST["gender"]);
        
            }
        }
        
        // Validate Form Data 
        function validateInput($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
          }
        
        
        if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
          {
          $servername = "localhost";
          $username = "root";
          $password = "";
          $dbname = "myDBPDO";
        
          try {
              $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
              // set the PDO error mode to exception
              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
              $sql = "INSERT INTO info (name, email, city, comment, gender)
              VALUES ('$name', '$email', '$city', '$comment', '$gender')";
              // use exec() because no results are returned
              $conn->exec($sql);
              echo "Success! Form Submitted!";
              }
          catch(PDOException $e)
              {
              echo $sql . "<br>" . $e->getMessage();
              }
        
          $conn = null;
        }
        
        ?>
        
        <!DOCTYPE HTML> 
        <html>
        <head>
        <style>
        .error {color: #FF0000;}
        </style>
        </head>
        <body> 
        
        
        
        
        <h2>PHP Form</h2>
        <p>Doesn't submit until the required fields you want are filled</p>
        
        
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
          <div class="error">
            <p><span>* required field</span></p>
            <div><?php echo $nameErr;?></div>
            <div><?php echo $emailErr;?></div>
            <div><?php echo $cityErr;?></div>
            <div><?php echo $commentErr;?></div>
            <div><?php echo $genderErr;?></div>              
          </div>
            <label for="name">Name:
              <input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
                <span class="error">*</span>
            </label>
            <label for="email">Email:
              <input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
                <span class="error">*</span>
            </label>
            <label for="city">city:
              <input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
               <span class="error">*</span>
            </label>
            <label for="comment">comment:
              <input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
                <span class="error">*</span>
            </label>
            <label for="gender">Gender:<br>
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
                <span class="error">*</span>
            </label>
           <input type="submit" name="submit" value="Submit"> 
        
        </form>
        </body>
        </html>
        

        如果您想将其重定向到另一个页面,请使用此选项,以便在刷新表单时不会再次将表单发送到您的 PDO 数据库。

        • 它不会提交到您的数据库,并且会停留在 HOME.PHP 页面上,直到您完成所有必填字段,并且还会在 HOME.PHP 页面上显示所需的输入错误消息。
        • 如果您忘记填写其中一个必填字段并提交,则不会清除所有字段。

        添加了“标题(“位置:welcome.php”);”在“$conn->exec($sql);”之后

        HOME.PHP

        <?php
        // define variables and set to empty values
        $nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
        $name = $email = $city = $comment = $gender = "";
        
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
          if (empty($_POST["name"])) {
            $nameErr = "Please add a name";
          } else {
            $name = validateInput($_POST["name"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";} 
            }
        
          if (empty($_POST["email"])) {
            $emailErr = "Please add an email";
          } else {
            $email = validateInput($_POST["email"]);
            // check if email is an email format
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
                $emailErr = "Invalid email format";
            }
          }
        
          if (empty($_POST["city"])) {
            $cityErr = "Please add your city";
          } else {
            $city = validateInput($_POST["city"]);
            // check if city only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
                $cityErr = "Only letters and white space allowed";
            }
          }
        
          if (empty($_POST["comment"])) {
            $commentErr = "Please add your comment";
          } else {
            $comment = validateInput($_POST["comment"]);
               // check if comment only contains letters and whitespace
               if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
                $commentErr = 'Only "/", "-", "+", and numbers';  
            }
          }
        
          if (empty($_POST["gender"])) {
            $genderErr = "Please pick your gender";
          } else {
            $gender = validateInput($_POST["gender"]);
        
            }
        }
        
        // Validate Form Data 
        function validateInput($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
          }
        
        
        if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
          {
          $servername = "localhost";
          $username = "root";
          $password = "";
          $dbname = "myDBPDO";
        
          try {
              $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
              // set the PDO error mode to exception
              $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
              $sql = "INSERT INTO info (name, email, city, comment, gender)
              VALUES ('$name', '$email', '$city', '$comment', '$gender')";
              // use exec() because no results are returned
              $conn->exec($sql);
              header("Location: welcome.php");
              }
          catch(PDOException $e)
              {
              echo $sql . "<br>" . $e->getMessage();
              }
        
          $conn = null;
        }
        
        ?>
        
        <!DOCTYPE HTML> 
        <html>
        <head>
        <style>
        .error {color: #FF0000;}
        </style>
        </head>
        <body> 
        
        
        
        
        <h2>PHP Form</h2>
        <p>Doesn't submit until the required fields you want are filled</p>
        
        
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
          <div class="error">
            <p><span>* required field</span></p>
            <div><?php echo $nameErr;?></div>
            <div><?php echo $emailErr;?></div>
            <div><?php echo $cityErr;?></div>
            <div><?php echo $commentErr;?></div>
            <div><?php echo $genderErr;?></div>              
          </div>
            <label for="name">Name:
              <input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
                <span class="error">*</span>
            </label>
            <label for="email">Email:
              <input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
                <span class="error">*</span>
            </label>
            <label for="city">city:
              <input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
            <span class="error">*</span>
            </label>
            <label for="comment">comment:
              <input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
                <span class="error">*</span>
            </label>
            <label for="gender">Gender:<br>
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
              <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
                <span class="error">*</span>
            </label>
           <input type="submit" name="submit" value="Submit"> 
        
        </form>
        </body>
        </html>
        

        WELCOME.PHP

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=\, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
        <body>
            <h1>Success! Form Submitted!</h1>
            <script type="text/javascript" src="js/main.js" ></script>
        </body>
        </html>
        

        【讨论】:

          【解决方案7】:

          你可以为 Errors 做一个数组,

          $errors = []; // empty array 
          
          if(isset($_POST['username']) && empty($_POST['username'])) {
             $errors['userName'] = "The userName is empty";
          }
          
          // then check if no errors , insert it to your DB :
          if(count($errors) <= 0) {
           // after filtering the username from XSS , insert it to DB.
          }else {
           // If there are ERRORS , even if one error :
           foreach($errors as $error) {
           // you can print all your errors 
          }
          }
          
          // or use then in onther place like this :
          if(isset($errors['username'])) { 
            echo $erros['username'];
          }
          

          或者你可以使用 JavaScript xmlHttpRequest , 阅读有关 preventDefault 函数的信息,

          【讨论】:

            【解决方案8】:

            您可以使用此功能停止表单:

            $("form").submit(function(a){
                a.preventDefault();
            });
            

            【讨论】:

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