how to store form validation errors in an array - php

If I have some basic form validations, (just using empty() for simplicities sake) and want to put those error messages into an array, how would I achieve this?
$errors = array();
$response = array();
if(empty($_POST['name'])) {
$errors['name'] = "Name required";
}
if(empty($_POST['email'])) {
$errors['email'] = "Email required";
}
$response['errors'] = $errors;
if(!empty($errors)) {
$response['success'] = false;
$response['message'] = "fail";
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Success</div>";
}
echo json_encode($response);
}

$message = [];
if(empty($_POST['name'])) {
array_push($message , "Name required <br />");
}
if(empty($_POST['email'])) {
array_push($message , "Email required <br />");
}
if(!empty($message)) {
foreach ( $message as $str)
echo "<div class='alert alert-danger'>" . $str . "</div>";
} else {
// success
}

Related

How can I short php code?

How can i modify my code to work "smarter" without so many if-loops? I am attaching what i have tried so far.
$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
$error2 = "fill in lname";
}
if (empty($_POST["street"])) {
$error3 = "fill in street";
}
if (empty($_POST["city"])) {
$error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
$error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
$error6 = "fill in country";
}
if (empty($_POST["email"])) {
$error7 = "fill in email";
}
if (empty($_POST["phone"])) {
$error8 = "fill in phone";
}
}
Thanks in advance!
Try this:
$errors = array();
$inputs = array("fname", "lname", "street", "city", "postcode", "country", "email", "phone");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST as $key => $arg) {
if(in_array($key, $inputs) && empty($arg)){
$errors[] = "fill in " . $key;
}
}
}
Please check this
$formfields = array('fname','lname','street','city','postcode','country','email','phone');
$errMsg = "";
if(isset($_POST) && count($_POST)>0){
foreach($_POST as $key => $val){
if(in_array($key, $formfields)){
if (empty($_POST[$key])) { $errMsg[] = "fill in ". $key; }
}
}
}
if(count($errMsg)>0)
echo implode("<br/>",$errMsg);

Form validation in php is not working properly

Can anyone tell me what wrong i am doing here ? Error shows only if the First name is blank, for the rest (e.g lastname/email/body) it's not working. EMail validation also not working.
$error = "";
if (empty($fanme)) {
$error = "First name must not be empty !";
}
elseif (empty($lname)) {
$error = "Last name must not be empty !";
}
elseif (empty($email)) {
$error = "email must not be empty !";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Invalid Email Address !";
}
elseif (empty($body)) {
$error = "Message field not be empty !";
}
else {
$msg = "ok";
}
}
if (isset($error)) {
echo "<span style='color:red'>$error</span>";
}
if (isset($msg)) {
echo "<span style='color:green'>$msg</span>";
}
It looks like you misspelled "$fname" in line 2 of your code above.

Error while validating numbers in php

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.

Form Validate with preg_match and send mail if all conditions are filled

//validate email
if(empty($email)){
$mailErr = "<div class='errors'>Email can not be empty.</div>";
}else{
if(!(preg_match("/^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/", $email))){
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
}
}
//validate message
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
}
if both validation are true then send mail. please help me. How can I write this condition. I want if both conditions are fulfill then send the mail.
// Validate email
if (empty($email)) {
$mailErr = "<div class='errors'>Email can not be empty.</div>";
} else if (!(preg_match("/^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/", $email))){
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
} else {
$valid_email = true;
}
// Validate message
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
}else{
$valid_message = true;
}
if ($valid_email && $valid_message) {
// Send the email
}
There is a short form to validate Email-Adresses using FILTER_VALIDATE_EMAIL and you can just safe a variable, which contains an error status.
$error = false;
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
$error = true;
}
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
$error = true;
}
if(!$error) {
//Send message here
}
You can also use a short form (but not checking both at the same time) without using a status variable:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
} else if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
} else {
//Send message here
}

Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?

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

Categories