PHP验证表单提交

时间:2014-08-24 09:14:29

标签: php forms validation

如何在表格完全填写之前停止发送给您的电子邮件。目前,当点击提交时,即使存在已通过我检查的PHP检查获取的验证错误:

代码:

  if (isset($_POST['submitButton'])) { 

    $fullName      = $_POST['fullName'];
    $myGender      = isset($_POST['myGender']) ? $_POST['myGender'] : ''; 
    $email         = $_POST['email'];
    $age           = $_POST['age'];
    $myDate        = isset($_POST['myDate']) ? $_POST['myDate'] : '';    
    $streetNum     = $_POST['streetNum'];
    $streetName    = $_POST['streetName'];
    $city          = $_POST['city'];
    $state         = $_POST['state'];   
    $postCode      = $_POST['postCode'];
    $movie         = $_POST['movie'];


    //You need to se the $var

    if (empty($fullName))
      {
        $errorfullName .= 'Please Enter Your Name';
      }

      if (!ctype_alpha(str_replace(array(" ", "-"), "",$fullName))) { 
            $errorfullName .= 'Your name should contain alpha characters only.';
      }

      if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
            $errorfullName .= 'First name should be within 3-40 characters long.';
        } 
/*  Check Gender) */

  if ($myGender != 'male' && $myGender != 'female') {
            $errormyGender .= 'Please select your gender.';


        }

  /* Check Email   */

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
     $erroremail .= 'Enter a valid email address.';
     }

/* Age */

if (intval($age) == '') {
        $errorage .= 'Please enter your current age';
        }
if (intval($age) < 3 OR intval($age) > 200){
        $errorage .= 'Age must be less than 200 years';
        }

if(intval($age) == "/^[0-9]$/" ){
          $errorage .= 'Must be numeric numbers';
          }

/*  check date using explode (breaks a string into an array.)if day is not 1-31, throw error*/

if(empty($myDate))
    {
        $errormyDate.= 'Please enter a current date';
    }

     $date_arr = explode ("-", $myDate);

     $dateSplit = array_slice($date_arr, 0,1);

     $dateYear = current($dateSplit);


    if($dateYear > date('Y'))
    {
        $errormyDate .= 'Sorry your not born in the future';
    }

/*  Check Address House Number if its not numeric, throw error */

if (intval($streetNum) == '') {
    $errorstreetNum .= 'Please add street Number';
    }
/* Street Name */   

     if (strlen($streetName) < 3 OR strlen($streetName) > 200) {
        $errorstreetName .= 'Street must be filled out and within 200 characters';
        }
 /*City Name */   

     if (strlen($city) < 3 OR strlen($city) > 200) {
        $errorcity .= 'City must be filled out and within 200 characters';
        }
 /*State Name */   

     if (strlen($state) < 3 OR strlen($state) > 200) {
        $errorstate .= 'State must be filled out and within 200 characters';
        }
/* Check postCode */

   if(intval($postCode) == "/^[0-9]$/" ){
      $errorpostCode .= 'Post Code must be numeric numbers';
      }
/* Check movie selection */

        if (trim($movie) === "select") {
            $errormovie .= 'Please select a favourite movie';
        }

if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){

            echo  '$errorsuccess .= 'Please complete all sections of the form'';
            }
            else {
            $success = "Thank you for submitting your form; We will be in contact soon";  
                    //send mail   
                    $to = "@yahoo.co.nz";  
                    $subject = "Php form data";  
                    $message = "<p>".$fullName."</p><p>".$myGender."</p><p>".$email."</p><p>".$age."</p><p>".$myDate."</p><p>".$streetNum."</p><p>".$streetName."</p><p>".$city."</p><p>".$state."</p><p>".$postCode."</p><p>".$movie."</p>";  
                    $from = "@yahoo.co.nz";  
                    mail($to,$subject,$message);  
                  }
}

3 个答案:

答案 0 :(得分:1)

在代码开头将$err之类的内容设置为false。检测到错误时将其设置为true。 (即使它已经是真的;只是设置它比检查更容易。)

然后,您可以在$err上调整最终结果。

答案 1 :(得分:1)

原因在于,即使您在上面已经完成了多项验证,但是之后都没有检查过它们是否失败/通过,您唯一的理智检查就在这里:

if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){

顺便说一下,它的一切都是无用的。

更简单的方法是首先创建一个数组来保存所有错误。

$errors = array();

然后,当您进行单独检查时,请将它们作为密钥,例如:

if (empty($fullName))
{
    $errors['fullname'] .= 'Please Enter Your Name';
}

if (intval($age) == '') {
    $errors['age'] .= ' Please enter your current age.';
}

if (intval($age) < 3 OR intval($age) > 200){
    $errors['age'] .= ' Age must be less than 200 years.';
}

if(intval($age) == "/^[0-9]$/" ){
    $errors['age'] .= ' Must be numeric numbers.';
}

然后你可以这样做:

if($errors){
    echo 'There are errors in the form. Please observe each of the errors and try again.'. PHP_EOL;
    foreach($errors as $idx => $error){
        echo ucfirst($idx). ': ' .$error;
    }
}

答案 2 :(得分:0)

看起来为了发送电子邮件,您只需要为每个输入字段(从$ fullName到$ movie)获得一个值。

在验证表单的地方(例如,当您使用if (empty($fullName))...时,如果表单未正确填写,则产生的错误总是不同的。除非您有某种理由,否则我只会坚持$formerror的一般错误变量。

然后在代码的最后一部分中,使用if($fullName...$movie == ''),您可以将其更改为if($fullName...$movie === '' AND !empty($formerror)),这样如果在验证表单期间发现任何错误,您就可以到echo $formerror,如果没有,电子邮件将发送。