Freedomeales
Freedomeales

Reputation: 11

PHP Validation form submit

How do you stop an email being sent to you before the form is fully completed. Currently when submit is clicked even though there are validation errors present that have been picked up via the PHP checks that I have in place:

Code:

  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);  
                  }
}

Upvotes: 0

Views: 118

Answers (3)

Bob Brown
Bob Brown

Reputation: 1502

Set something like $err to false at the beginning of the code. Set it to true when an error is detected. (Even if it's already true; just setting it is easier than checking.)

Then, you can condition the final result on $err.

Upvotes: 1

Alex Yorke
Alex Yorke

Reputation: 48

It looks like that in order to send the email, you only need to have a value for each of your input fields (from $fullName to $movie).

Where you are validating the form (for example, when you use if (empty($fullName))..., the error that is produced if the form isn't filled out correctly always differs. Unless you have some kind of reason for this, I would just stick to a generic error variable of $formerror.

Then in the final section of your code, where you use if($fullName...$movie == ''), you could change this to if($fullName...$movie === '' AND !empty($formerror)) so that if any errors were picked up during the validating of the form, you would be able to echo $formerror and if not, the email would send.

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

The reason being is that you even though you have several validations completed in the above, none of them are later checked to see if they failed/passed, your only sanity check is here:

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

Which its self is pretty useless all together, by the way.

A simpler way for this would be to first create an array to hold all the errors.

$errors = array();

Then when you do your individual checks, make them a key, for example:

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

And

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.';
}

Then later you can do:

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;
    }
}

Upvotes: 1

Related Questions