php验证无法处理表单提交

时间:2013-11-18 13:39:05

标签: php html validation

我正在处理一个字段很少的表单,我已经在某些字段上应用了验证,例如。名称,电子邮件和性别,验证在同一页面上正常工作但当我点击提交时,它会移动到另一页而不验证字段

$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = $pick = $return = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "* Name is required";}
else
{$name = test_input($_POST["name"]);}
if (!preg_match("/^[a-zA-Z ]*$/",$name))
 {
 $nameErr = "* Only letters and white space allowed"; 
 }

 if (empty($_POST["email"]))
 {$emailErr = "* Email is required";}
 else
  {
  $email = test_input($_POST["email"]);
 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
   {
   $emailErr = "Invalid email format"; 
   }
 }

 if (empty($_POST["gender"]))
{$genderErr = "* Gender is required";}
 else
{$gender = test_input($_POST["gender"]);}
}
if (empty($_POST["pick"]))
{$pick = "";}
 else
  {$pick = test_input($_POST["pick"]);}

 if (empty($_POST["return"]))
{$return = "";}
 else
{$return = test_input($_POST["return"]);}

function test_input($data)
 {
 $data = trim($data);
 $data = stripslashes($data);
 $data = htmlspecialchars($data);
 return $data;
 }
 ?>

并且继承了表单的html

<p><span class="error"></span></p>
<form method="post" action="submit.php<?php echo             htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error"><?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email" value="<?php echo $email; ?>">
 <span class="error"><?php echo $emailErr;?></span>
<br><br>
Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<span class="error"><?php echo $genderErr;?></span>
 <br><br>
 <input type="checkbox" name="pick"> I would like to specify the Additional                    journey pickups
  <br><br>
  <input type="checkbox"name="return">Return journey required ?<br />
  <br><br>
  <input type="submit" name="submit" value="Submit">
  </form>

任何帮助都会受到高度赞赏

3 个答案:

答案 0 :(得分:0)

<form method="post" action="submit.php<?php echo             htmlspecialchars($_SERVER["PHP_SELF"]);?>">

这条线是错的。因为$_SERVER['PHP_SELF']是您的PHP文件,所以它将是:

submit.phpmyphpfile.php

将其更改为:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

答案 1 :(得分:0)

这是正常行为,因为PHP在服务器端运行,因此必须首先执行对给定页面的请求(例如,来自表单action的页面)。然后PHP将接收值并可以验证它们。如果出现错误,您可以根据需要将用户重定向到表单并向他显示错误。

如果您想在发送前进行验证,则应使用JavaScript,但不能依赖它。用户始终可以跳过此验证,因此即使您使用JavaScript,也必须使用服务器端验证。

首先,你应该解决@Legionar所描述的问题。

答案 2 :(得分:0)

<form method="post" action="submit.php<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

此行表示您将此页面发布到submit.php,submit.php将处理您的请求 所以你可能需要在submit.php中添加验证码