I'm currently building a very small 'contact' form for use on a personal site.
The form works, and each validation 'if' statement works individually, however, if for example I input a valid email address and phone number but leave the message blank, the email still sends and I get the success message.
My guess would be to include the small 'if' statements into the one checking whether my required fields are not empty, though i'm not sure how to do this correctly as it is nesting multiple 'if's into one.
Cheers
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
?>
<!-- Display red error box or green success box depending on which is true -->
<?php if(!empty($errors)): ?>
<div class="validationbox | errorsbox">
<?php echo $errors; ?>
</div>
<?php elseif(empty($errors)): ?>
<div class="validationbox | successbox">
<?php echo $success; ?>
</div>
<?php
$message = ''; // Blank message to start with so we can append to it.
// Construct the message
$message .= "
Name: {$_POST['thename']};
Email: {$_POST['email']};
Number: {$_POST['number']};
Enquiry-type: {$_POST['enquiry-options']};
Message: {$_POST['comments']};
";
// test#testdomain.com
$to = 'test-email-deleted-for-stackoverflow';
$subject = 'Message from Portfolio';
$from = $_POST['thename'];
// YourSite#domain.com
$fromEmail = 'test-email-deleted-for-stackoverflow';
$header = 'From: ' . $from . '<' . $fromEmail . '>';
mail($to,$subject,$message,$header);
?>
<?php endif; ?>
<?php endif; ?>
Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
You shouldn't do that, just leave error messages to whatever it previously was. This way, when you get to the end, $errors will contain a string of all the error messages combined. Since there could be multiple messages, you may want to put a break a the end of each one:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.<br>";
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address<br>";
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number<br>";
}
In the case of email, you may want to only display the 'invalid email address' only when something was actually filled in, so you could also check to ensure there is something in there, before you determine if the format is valid or not:
if (!empty($email) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
Based on the information Supplied, i think you should use a complex if-elseif-else statement like so:
`if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
} `
in your particular case:
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors = 'Error:invalid email';
}elseif(!preg_match("/^\(?0( *\d\)?){9,10}$/", $number){
$errors .= "Error: Invalid phone number";
} else {
//Do this on successful validation comes here
}
try below code it helps you.
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
}
?>
Related
I would really appreciate if someone could help me with my 2 questions. I have a contact form and I want to:
1) show a confirmation message to the user, once he clicks submit.
2) send a confirmation e-mail to the user, once he clicks submit.
My contact_process.php is:
<?php
include dirname(dirname(__FILE__)).'/mail.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'email_validation.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
if(!$error)
{
$mail = mail(CONTACT_FORM, $subject,
"From: ".$name." <".$email.">\r\n");
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
And my email_validation.php is:
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
If anyone could help with adding the missing code, that would be amazing. I am a beginner at this.
Thank you!
Sorin
I am new to PHP and currently getting back to HTML. I have made a form and have the data sent and validated by PHP but I am trying to send the email to myself only after the data had been validated and is correct. Currently if the page is loaded I think it send an email and it will send whenever I hit submit without the data being correct.
Here is where I validate the data:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
function validate_info($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Sorry its a little lengthy.
Here is where I try to send the email. I have tried two different attempts and both have the same result.
<?php
if (!empty($fnameErr) || !empty($lnameErr) || !empty($subjectErr) || !empty($emailErr) || !empty($commentErr) || !empty($websiteErr) || !empty($findoptionErr))
{
echo "Sent!!";
}else
{
echo"Not Sent!!";
}
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
?>
Once again sorry for the length. Thanks in advance also sorry if this is a double question or not described enough I am also new to stack overflow.
Please try:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Initialize variable used to identify form is valid OR not.
$formValid = true;
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$formValid = false;//Form not validate
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$formValid = false;//Form not validate
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$formValid = false;//Form not validate
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$formValid = false;//Form not validate
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$formValid = false;//Form not validate
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$formValid = false;//Form not validate
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$formValid = false;//Form not validate
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$formValid = false;//Form not validate
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
//If every variable value set, send mail OR display error...
if (!$formValid){
echo"Form not validate...";
}
else {
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
if($sendMail){
echo "Mail Sent!!";
}
else {
echo "Mail Not Sent!!";
}
}
function validate_info($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I edit my answer as per some change. Now this code only allow send mail if form required fields are not empty and all fields value are valid as per your validation.
Let me know if there is any concern.!
from what i was able to conceive, u are
trying to apply 'OR' in if condition- should be changed to AND i.e. change || to &&
you are checking for not empty error variables... which should be changed to verify if they all are empty or not.
if (empty($fnameErr) && empty($lnameErr) && empty($subjectErr) && empty($emailErr) && empty($commentErr) && empty($websiteErr) && empty($findoptionErr))
{
echo "sent";
}
Instead of writing lengthy conditions.
Assign all error messages to a single variable and append errors to it ($errorMsg). You can avoid lengthy if else ladder by doing this.
Change empty($_POST["email"]) to !isset($_POST["email"]) - In all statements.
Then update the condition to following,
<?php
if($errorMsg == ''){
//Make the message.
$message ="
First Name: ".$fname.".\n
Last Name: ".$lname."\n
Website: ".$website."\n
Did They Like the Site? ".$likedsite."\n
How They Found Us. ".$findoption."\n
Question/Comments:\n
".$comments." ";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
}else{
// Show $errorMsg
}
?>
Make it simple, I hope this helps.
I m trying to validate only numbers in php but it is displaying error message.I want user to enter a valid mobile number,batch where only 4 numbers as to be entered. No characters should be entered.Please tell me whats the error in the code.
Here is the code
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
}
if (!preg_match('/^[0-9]+$/', $batch)) {
$error .= "Enter a Valid Number. <br/>";
}
else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
}
if (!preg_match('/^[0-9]+$/', $mobile)){
$error .= "Enter A Valid Number. <br/>";
}
else {
$error .= "You didn't type your Mobile Number. <br />";
}
(!preg_match('/^[0-9]{4}$/', $batch)
Use this if you want to validate for only 4 numbers.
I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if ( ! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}
I have:
if(isset($_POST['submit'])) {
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
} else if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
} else if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.
Any ideas? Thank you
You could collect all errors in an array like this:
if (isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo 'There were some errors: ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
With this you can check all requirements and report all errors and not just the first one.
use:
$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }
if($error > 0)
{
// Do actions for your errors
}
else
{
// Send Email
}
you can use try...catch statements for error checking like this.
whenever you encounter a condition where an error should be generated, you can use throw new Exception clause.
Use a dirty flag. Check them all and append the message to the dirty variable.
Try this:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = 'Missing Name';
}
if(empty($phone) || empty($email)) {
$errors[] = 'You must insert a phone number or email';
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = 'Please Insert a valid Email';
}
if (!empty($errors)) {
for ($i = 0; i < count($errors); $i++) {
echo sprintf('<span class="error">ERROR: %s</span><br/>', $errors[$i]);
}
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
if(isset($_POST['submit'])) {
$valid = true;
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
$valid = false;
}
if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
$valid=false;
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
$valid = FALSE;
}
if($valid) {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}