在php中验证表单

时间:2017-01-11 10:05:29

标签: php validation

我在php中有一个表单,我需要验证表单。所以我尝试了这些代码,但没有得到任何验证消息。什么都没有显示出来。我得到的错误是什么

<form class="" method="post" action="">
<div class ="col-md-3" style="clear:both;">
            <label style="font-size:12px;"> Your Name:</label>
            <input type="text" id="AS_Name" name="AS_Name" />
            <span style="font-size:12px; color:red;"> <?php echo $nameError; ?> </span>
            </div>
    <input  id="AstroSend" type="submit" Value="Send" name="submit" />
   </form>

<?php
 $nameError ="";
if(isset($_POST['submit'])) {

if (empty($_POST["AS_Name"]))
    {   

    $nameError = "Name is required";

    } 
else 
    {

    $name = test_input($_POST["AS_Name"]);
    // check name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) 
    {
    $nameError = "Only letters and white space allowed";
    }
    } ?>

如果我在if循环内回显,则显示消息。但我希望span本身的验证消息。

3 个答案:

答案 0 :(得分:0)

您只需要检查html上方的验证,而不是下面的内容:)

答案 1 :(得分:0)

进行以下更改

<?php
 $nameError ="";
 if(isset($_POST['submit'])) 
 {
   if (empty($_POST["AS_Name"]))
   {   
    $nameError = "Name is required";
   }

  else 
 {

  $name = test_input($_POST["AS_Name"]);
// check name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) 
     {
       $nameError = "Only letters and white space allowed";
     }
   } 
  }
?>

<form class="" method="post" action="">
<div class ="col-md-3" style="clear:both;">
        <label style="font-size:12px;"> Your Name:</label>
        <input type="text" id="AS_Name" name="AS_Name" />
        <span style="font-size:12px; color:red;"> <?php echo $nameError;?> </span>
          </div>
       <input  id="AstroSend" type="submit" Value="Send" name="submit" />
       </form>

答案 2 :(得分:0)

我不是那个投票的人,但在你的其他地方是错误的@coder。

我的工作正常

NewBie可以查看

<?php
$nameError ="";
if(isset($_POST['submit'])) 

{

if (empty($_POST["AS_Name"]))
{   
$nameError = "Name is required";

} 其他 { $ name = $ _POST [“AS_Name”];

if (!preg_match("/^[a-zA-Z ]*$/",$name)) 

{

$nameError = "Only letters and white space allowed";

}

} 

}

?>
<form class="" method="post" action="">

<div class ="col-md-3" style="clear:both;">
            <label style="font-size:12px;"> Your Name:</label>
        <input type="text" id="AS_Name" name="AS_Name" />
        <span style="font-size:12px; color:red;"> <?php echo $nameError;?> </span>

</div>
<input  id="AstroSend" type="submit" Value="Send" name="submit" />
   </form>