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

问题描述 投票:2回答:6

我是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
6个回答
2
投票

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

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

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会让你的生活更轻松


1
投票

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


0
投票

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


0
投票

如果任何字段为空,我需要表单不提交为什么你不尝试这个..

<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

0
投票

这是使用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页面上显示所需的输入错误消息。
  • 如果您忘记填写其中一个必填字段并提交,则不会清除所有字段。

添加了“标题(”位置: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>
© www.soinside.com 2019 - 2024. All rights reserved.