0

Okay, I have a php form. Standard, fill it out, submit, check for errors, pass and send email, redirect to thank-you page.

I have the form working well, except for validation. If I fill out the form and hit send I get the email and the page redirects. If I don't fill out the form and hit send, I don't get errors, I don't get an email, but the page does redirect.

Why is my validation not working? Am I missing a link between the email part and the validation part of the PHP?

<?php
// define variables and set to empty values
 $company = $fname = $lname = $email = $phone = $address = $city = $provincestate = $country = $location = $size = $type = $message ="";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $company = test_input($_POST["company"]);
  $fname = test_input($_POST["first-name"]);
  $lname = test_input($_POST["last-name"]);
  $email = test_input($_POST["email"]);
  $phone = test_input($_POST["phone"]);
  $address = test_input($_POST["address"]);
  $city = test_input($_POST["city"]);
  $provincestate = test_input($_POST["provincestate"]);
  $country = test_input($_POST["country"]);
  $location = test_input($_POST["location"]);
  $size = test_input($_POST["size"]);
  if(isset($_POST["type"])){ $type = $_POST["type"];}
  $message = test_input ($_POST["message"]);
}

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

// define variables and set to empty values
 $companyErr = $fnameErr = $lnameErr = $emailErr = $phoneErr = $addressErr = $cityErr = $provincestateErr = $countryErr = $locationErr = $sizeErr = $typeErr = $messageErr ="";
 $company = $fname = $lname = $email = $phone = $address = $city = $provincestate = $country = $location = $size = $type = $message ="";


if ($_SERVER["REQUEST_METHOD"] == "POST") {

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

   if (empty($_POST["first-name"])) {
    $fnameErr = "First name is required";
  } else {
    $fname = test_input($_POST["first-name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed"; 
    }
  }     

  if (empty($_POST["last-name"])) {
    $lnameErr = "Last name is required";
  } else {
    $lname = test_input($_POST["last-name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters allowed"; 
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }

  if (empty($_POST["phone"])) {
    $phoneErr = "Phone number is required";
  } else {
    $phone = test_input($_POST["phone"]);
    // check if phone number only contains 10 digits with no formatting
    if (!preg_match("/^[0-9]{10}+$/",$phone)) {
      $phoneErr = "Only enter a 10 digit number"; 
    }
  }

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

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

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

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


  if (empty($_POST["location"])) {
    $locationErr = "Location is required";
  } else {
    $location = test_input($_POST["location"]);
    // check if location only contains letters
    if (!preg_match("/^[a-zA-Z ]*$/",$location)) {
      $locationErr = "Please enter a city"; 
    }
  }

 if (empty($_POST["size"])) {
    $sizeErr = "Please enter a number";
  } else {
    $size = test_input($_POST["size"]);
  }

  if (empty($_POST["type"])) {
    $typeErr = "Please select 1";
  } else {
    $type = test_input($_POST["type"]);
  }

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

$myemail = '';//<-----Put Your email address here.

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $to = $myemail; 
    $email_subject = "Inquiry from: $fname $lname";
    $email_body = "You have received a new inquiry from:".
    "\n
     \n Name: $fname $lname \n Email: $email \n Phone Number: $phone
     \n Address: $address \n City: $city \n Province/State: $provincestate \n Country: $country
     \n I have a project in: $location \n The project type is: $type  \n The estimated project size is: $size
     \n Message: $message"; 

    $headers = "From: $myemail\n"; 
    $headers .= "Reply-To: $email";

    mail($to,$email_subject,$email_body,$headers);

    //redirect to the 'thank you' page
    header('Location: thankyou.html');
    exit();
}
?>
0

3 Answers 3

1

You dont have any return at the end of the validation, so it just goes through them, and access the last if statement (where the mail is sent), reaching the header('Location: thankyou.html') line.

Edit:

You should redirect to the main form (for example, using header('Location: yourform.html') when any of the validation don't work.

if (empty($_POST["last-name"])) {
    $lnameErr = "Last name is required";
    header('Location: yourform.html');
} else {
    $lname = test_input($_POST["last-name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
        $lnameErr = "Only letters allowed";
        header('Location: yourform.html'); 
    }
}

Other option is to gather all the error (like, having a error count), then redirect if any error found, showing them.

if (empty($_POST["last-name"])) {
    $lnameErr = "Last name is required";
    $errCount++;
} else {
    $lname = test_input($_POST["last-name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
        $lnameErr = "Only letters allowed";
        $errCount++;
    }
}
...
if($errCount > 0){
    ...
    header('Location: yourform.html');
}

Another option is to work the validations directly in the form using JavaScript.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you elaborate? I don't have a lot of knowledge of php. I understand what you are saying, but what would the 'return' be?
CamiloR - I simply took this php code from a tutorial somewhere and modified it, I've posted elsewhere and they don't agree with the structure. The thing that is giving me the headaches is the email portion. If I take this out, the validation executes and my red error messages appear if the fields arent filled in. Why when I add the email portion, the validation is ignored. I need to add something to the email portion, but I just can't figure it out...
1

Validation doesn't work because there is nothing that outputs a validation message, e.g.:

if($emailErr != '') die($emailErr);

I advise you to create a function like this:

$errorMessages = array();
function errormsg($message) {
  $errorMessages[] = $message;
}

Then, instead of writing the vaidation messages in variables like $fnameErr = "First name is required"; call this function:

errormsg('First name is required');

At the end then you can output the messages if there was an error instead of sending the email:

if(count($errorMessages) > 0) {
  /* output the messages */
  print_r($errorMessages); /* for illustration */
} else {
  /* send the email */
}

Edit Reading the comments I conclude that there is more code concerning validation that you haven't shown us yet. So if you want to use your current logic you need a if statement around the email sending part, that checks wether there has been a validation error.

if($fnameErr != "" && $lnameErr != "" /* and so on */) {
  /* send email */
}

5 Comments

It should rather be a comment than answer.
I took out the email for posting here.
@AliNfr Why, the question is: Why is my validation not working?
Okay heres something that happens: If I remove the email sending part at the bottom, and its just the validation part, the validation executes when I hit submit. So if fields aren't filled in, red text comes up beside it (span) and says please fill out etc. Why when the email part is out of the equation the validation works? As soon as I put the email part back in, the validation stops.
because you send the email anyway, if there is a validation error or not. And in the email-part is a exit().
0
$myemail = '';//<-----Put Your email address here.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //add these error showing
    if($companyErr) exit("Error : $companyErr");
    if($fnameErr) exit("Error : $fnameErr");
    //repeat all those variables here......

    $to = $myemail; 
    $email_subject = "Inquiry from: $fname $lname";
    $email_body = "You have received a new inquiry from:".
    "\n
     \n Name: $fname $lname \n Email: $email \n Phone Number: $phone
     \n Address: $address \n City: $city \n Province/State: $provincestate \n Country: $country
     \n I have a project in: $location \n The project type is: $type  \n The estimated project size is: $size
     \n Message: $message"; 

    $headers = "From: $myemail\n"; 
    $headers .= "Reply-To: $email";

    mail($to,$email_subject,$email_body,$headers);

    //redirect to the 'thank you' page
    header('Location: thankyou.html');
    exit();
}

1 Comment

I've implemented this - and I understand what its doing. But, I have all of the other php code at the top to display errors directly on the same page ie) <label> Location</label> <span class="error">* <?php echo $locationErr;?></span> SO why can't I show the validation errors on the same page - instead of your method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.