PHP不会显示表单验证的错误消息

时间:2012-06-14 15:47:07

标签: php validation

我不明白为什么变量$errorMessage不会设置数组错误。

我正在尝试进行表单验证。这个PHP位于页面顶部register.php

这是我正在尝试处理的页面。我希望我能解决这个问题!

<?php
   session_start();
   // include("includes/connect.php");
   include ("includes/html.php");


   if (isset($_POST['submit'])){
      $error = array(); 

      //username
      if (empty($_POST['username'])){
         $error[] = 'Please Enter a Username';
      }
      else if (ctype_alnum ($_POST['username'])){
         $userName = $_POST['username'];
      } 
      else {
         $error[] = 'Username Must Consist Letters and Numbers Only';
      }

      //email
      if (empty($_POST['email'])){
         $error[] = 'Please Enter an Email';
      } 
      else if (!preg_mach ("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)
↪*(\.[a-z]{2,3})$",$_POST['email'])) {
         $email = mysql_real_escape_string ($_POST['username']);
      } 
      else {
         $error[] = 'Your Email Address is Invalid';
      }

      //password
      if (empty($_POST['password'])){
         $error[] = 'Please Enter a password';
      } 
      else if ($_POST['password']!==$_POST['password2']){
         $error[] = 'Your Password Did Not Match';
      }
      else {
         $password = mysql_real_escape_string($_post['password']);
      }
   }

   if (empty ($error)){
      //good info
   }
   else {
      $errorMessage = '<span class="error">';
      foreach ($error as $key => $e){
         $errorMessage.= "$e";
      }
      $errorMessage.= '</span> <br /><br />';
   }

?>

2 个答案:

答案 0 :(得分:2)

您的$error数组已编入索引,因此您应该使用:

foreach ($error as $e){

}

答案 1 :(得分:0)

因为您正在检查错误数组是否为空?。如果有任何错误消息,它将不会为空,您将跳过整个消息构建块。

if (!empty ($error)){
    ^---- if NOT EMPTY