我想知道如何在验证失败时停止表单提交


I would like to know how to stop form submission when the validation fails?

我是 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 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']);
?>

如果要访问欢迎页面中的所有变量。 只是像下面这样的代码

首页.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']);
?>

欢迎.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'];
?>

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

给表单一个像这样的 id

方法="发布" 操作="欢迎.php" id=">form1">

和所有表单元素的 ID

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

返回 false 停止提交。

如果你打算做前端而不仅仅是php,你应该真的去jquery,这将使你的生活更轻松

Javascript 是客户端,

PHP 是服务器端,所以直到没有按下提交按钮到"将数据发布到服务器",然后从那里使用 php 来验证表单.. 检查字段执行不同的操作,如数据库插入、计算等,您无法将响应发送回客户端并告诉他您在这里得到了此错误,我不会处理此类数据。好吧,您可以使用 ajax 在服务器端实时验证表单。最好的方法是验证客户端,然后在使用来自客户端的所有数据之前,因为每个人都撒谎,所以你在服务器上做另一个检查。下面是一个示例。

这是使用 PHP 对 PDO 数据库执行此操作的另一种方法:

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

我在连接中添加了一个 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页面。
  • 如果您忘记填写必填字段之一并提交,它不会清除所有字段。

在"$conn->exec($sql(;"之后添加了"header("Location: welcome.php"(;">

家。.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>

欢迎。.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>

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

我需要表单

不会提交,如果任何字段为空,为什么不试试这个。.

<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

你可以为错误做一个数组,

$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 ,阅读有关预防默认函数的信息,

您可以使用

此函数停止表单:

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