Daniel Gomez
Daniel Gomez

Reputation: 13

show multiple error messages when more than one field is invalid

The way I have written my code there is only one error message that pops up when more than one field is invalid. I would like to have my code show multiple error messages when multiple fields are invalid. How would i go about doing this? for example: first_name and last_name are invalid, however only first name error message shows

here is my full code below:

<?php 

// define variables and set to empty values
$first_nameErr = $last_nameErr = $emailErr = $messageErr  = "";
$first_name = $last_name = $email = $from = "";

if($_SERVER["REQUEST_METHOD"] == "POST"){
  $to = "[email protected]"; // this is your Email address
     // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
     $from = $_POST['email'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
   if (empty($_POST["first_name"])){
    $first_nameErr = " First name is required";

  }
  else if ((!preg_match("/^[a-zA-Z-' ]*$/",$first_name))) {
  $first_nameErr = "Please type in only letters and whitespace";
}


   else if(empty($_POST["last_name"])){
    $last_nameErr = " Last name is required";
  }
    else if ((!preg_match("/^[a-zA-Z-' ]*$/",$last_name))) {
    $last_nameErr = "Please type in only letters and whitespace";
  }
     else if (empty($_POST["email"])) {
            $emailErr = "Email is required";
          }
          
       else if (!(filter_var($from, FILTER_VALIDATE_EMAIL))) { 
         
            $emailErr = "Email is invalid";
}

             else if (empty($_POST["message"])) {
                $messageErr = "message is required";
              }

 

                else {
                  
                  mail($to,$subject,$message,$headers);
                  mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
                  echo '<script>alert("Mail Sent. Thank you , we will contact you shortly.")</script>';

                
    }
    


   
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE HTML>
<!--
    Industrious by TEMPLATED
    templated.co @templatedco
    Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
-->
<html>
    <head>
        <title>Generic Page - Industrious by TEMPLATED</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link rel="stylesheet" href="assets/css/main.css" />
    </head>
    <body class="is-preload">

        <!-- Header -->
            <header id="header">
                <a class="logo" href="index.html">Test</a>
                <nav>
                    <a href="#menu">Menu</a>
                </nav>
            </header>

        <!-- Nav -->
            <nav id="menu">
                <ul class="links">
                    <li><a href="index.html">Home</a></li>
                    <li><a href="elements.html">Elements</a></li>
                    <li><a href="aboutme.html">About me</a></li>
                </ul>
            </nav>

        <!-- Heading -->
            <div id="heading" >
                <h1>Contact Us</h1>
            </div>

        <!-- Main -->
            <section id="main" class="wrapper">
                <div class="inner">
                    <div class="content">
                     <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* </span>
First Name: <input type="text" name="first_name" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/><span class="error"><?php echo $first_nameErr;?></span>

<br>
<span class="error">* </span>
 Last Name:<input type="text" name="last_name" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/><span class="error"><?php echo $last_nameErr;?></span>
<br>
<span class="error">* </span>
Email: <input type="text" name="email"><span class="error" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/><?php echo $emailErr;?></span>
<br>
<span class="error">* </span>
Message:<br><textarea rows="5" name="message" cols="30" ><?php if (isset($_POST['message'])) echo $_POST['message']; ?></textarea><span class="error"><?php echo $messageErr;?></span>
</br>

<input type="submit" name="submit" value="Submit">



  

  </form>

                    </div>
                </div>
            </section>
            <!-- Footer -->
            <footer id="footer">
                <div class="inner">
                    <div class="content">
                        <section>
                            <h3>Accumsan montes viverra</h3>
                            <p>Nunc lacinia ante nunc ac lobortis. Interdum adipiscing gravida odio porttitor sem non mi integer non faucibus ornare mi ut ante amet placerat aliquet. Volutpat eu sed ante lacinia sapien lorem accumsan varius montes viverra nibh in adipiscing. Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing sed feugiat eu faucibus. Integer ac sed amet praesent. Nunc lacinia ante nunc ac gravida.</p>
                        </section>
                        <section>
                            <h4>Sem turpis amet semper</h4>
                            <ul class="alt">
                                <li><a href="#">Dolor pulvinar sed etiam.</a></li>
                                <li><a href="#">Etiam vel lorem sed amet.</a></li>
                                <li><a href="#">Felis enim feugiat viverra.</a></li>
                                <li><a href="#">Dolor pulvinar magna etiam.</a></li>
                            </ul>
                        </section>
                    <section>
                            <h4>Magna sed ipsum</h4>
                            <ul class="plain">
                                <li><a href="#"><i class="icon fa-twitter">&nbsp;</i>Twitter</a></li>
                                <li><a href="#"><i class="icon fa-facebook">&nbsp;</i>Facebook</a></li>
                                <li><a href="#"><i class="icon fa-instagram">&nbsp;</i>Instagram</a></li>
                                <li><a href="#"><i class="icon fa-github">&nbsp;</i>Github</a></li>
                            </ul>
                        </section>
                    </div>
                    <div class="copyright">
                        &copy; Untitled. Photos <a href="https://unsplash.co">Unsplash</a>, Video <a href="https://coverr.co">Coverr</a>.
                    </div>
                </div>
            </footer>

        <!-- Scripts -->
            <script src="assets/js/jquery.min.js"></script>
            <script src="assets/js/browser.min.js"></script>
            <script src="assets/js/breakpoints.min.js"></script>
            <script src="assets/js/util.js"></script>
            <script src="assets/js/main.js"></script>
        </body>
        </html>

Upvotes: 0

Views: 970

Answers (4)

FluffyKitten
FluffyKitten

Reputation: 14312

You have a few issues with your code, and there are also easier ways to handle the error messages.

1. The reason you are only getting one error message is that you are using else if for every check. You only need to use that for checks on the same input, e.g. if first_name is empty {} else if first name has invalid chars{}

2. You can add the errors to an array, this makes it much easier to process. Add each with the input name as the key for easy retrieval, e.g.

      if (empty($_POST["first_name"]))
        $errors["first_name"] = " First name is required";

      <span class="error"><?php echo $errors["first_name"];?></span> 

3. If you want to convert the error array to a string to be displayed all in one place, you can use implode, e.g.

$error_str = implode("<br>", $errors);
echo "<p>$error_str</p>";

4. Then at the end, you can simply check if the array has errors - if it is empty, there were no errors so we're good to go

if (empty($errors)){
    /* No errors, so send email */
}

Update: To make it easier to get errors from the array, you can create a function to use like this - you can even output your span to eliminate duplication:

function show_error_msg($errors, $field){
    if ($errors[$field]) 
        '<span class="error">'.echo $errors[$field].`</span>`;
}

Here is the part of your code changed to use the error array:

<?php
$errors = array();

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

   /* Fill your variables here from the $_POST */

   /* VALIDATION */
   /* First Name validation */
   if (empty($_POST["first_name"])){
     $errors["first_name"] = " First name is required";
   }
   else if ((!preg_match("/^[a-zA-Z-' ]*$/",$first_name))) {
     $errors["first_name"] = "Please type in only letters and whitespace";
   }

   /* Last Name validation */
   if(empty($_POST["last_name"])){
     $errors["last_name"] = " Last name is required";
   }
   else if ((!preg_match("/^[a-zA-Z-' ]*$/",$last_name))) {
     $errors["last_name"] = "Please type in only letters and whitespace";
   }

   /* Email validation */
   if (empty($_POST["email"])) {
     $errors["email"] = "Email is required";
   }
   if (!(filter_var($from, FILTER_VALIDATE_EMAIL))) { 
    $errors["email"] = "Email is invalid";
   }
  
   /* Message validation */
   if (empty($_POST["message"])) {
     $errors["message"] = "message is required";
   }
  
   /* If out error array is empty, we're good to go...*/
   if (empty($errors)){
     /* do stuff...*/
   }
}
  
/* Turn the array into a string for display if required */
$error_str = implode("<br>", $errors);
?>

And the HTML form:

<span class="error">* </span>
First Name: 
<input type="text" name="first_name"  value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/>
<?php show_error_msg($errors, "first_name");?>
<br>

<span class="error">* </span>
 Last Name:
 <input type="text" name="last_name" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>"/>
 <?php show_error_msg($errors, "last_name");?>
<br>

<span class="error">* </span>
Email: <input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"/>
<?php show_error_msg($errors, "email");?>
<br>

<span class="error">* </span>
Message:<br><textarea rows="5" name="message" cols="30" ><?php if (isset($_POST['message'])) echo $_POST['message']; ?></textarea>
<?php show_error_msg($errors, "message");?>
</br>

NOTE: Other Errors

You also have a few other errors in your code, for example you are checking for the first name to show in the last name and the email fields:

Last Name:<input type="text" name="last_name" 
     value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/>

Email: <input type="text" name="email">
    <span class="error" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/><?php echo $emailErr;?></span>

Upvotes: 1

Andrew Chamamme
Andrew Chamamme

Reputation: 165

You are only seeing one error message because you have the validation rules wrapped in if..else statements. This means that only one validation block will ever be executed. What you can do is to have each validation rule in its own if statement and introduce a new boolean variable to indicate if an error was found before sending the mail.

The code below should resolve your issue;

<?php
// define variables and set to empty values
$first_nameErr = $last_nameErr = $emailErr = $messageErr  = "";
$first_name = $last_name = $email = $from = "";

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $isValid = true; // new variable

    $to = "[email protected]"; // this is your Email address
    // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $from = $_POST['email'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    if (empty($_POST["first_name"])){
        $first_nameErr = " First name is required";
    }

     if ((!preg_match("/^[a-zA-Z-' ]*$/",$first_name))) {
        $first_nameErr = "Please type in only letters and whitespace";
         $isValid = false;
    }


     if(empty($_POST["last_name"])){
        $last_nameErr = " Last name is required";
         $isValid = false;
    }
     if ((!preg_match("/^[a-zA-Z-' ]*$/",$last_name))) {
        $last_nameErr = "Please type in only letters and whitespace";
         $isValid = false;
    }
     if (empty($_POST["email"])) {
        $emailErr = "Email is required";
         $isValid = false;
    }

     if (!(filter_var($from, FILTER_VALIDATE_EMAIL))) {

        $emailErr = "Email is invalid";
         $isValid = false;
    }

     if (empty($_POST["message"])) {
        $messageErr = "message is required";
         $isValid = false;
    }



    if( $isValid == true) {

        mail($to,$subject,$message,$headers);
        mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
        echo '<script>alert("Mail Sent. Thank you , we will contact you shortly.")</script>';

    }

  // You can also use header('Location: thank_you.php'); to redirect to another page.

}
?>

Upvotes: 0

Rob Ruchte
Rob Ruchte

Reputation: 3707

The way I have always done this is to have one array that holds all of the validation errors. Each field that has validation errors gets an element in the errors array that holds an array of all the errors for that field. Then in the markup, I check to see if the errors array has a key that matches the field name, and if so, I iterate through the errors and display them. This lets you do things like set an error class on the field container by checking for the presence of the key, then list the individual errors inside the container.

<?php
// Define an array the we can collect our errors in
$errors = [];
if (empty($_POST["first_name"]))
{
    // Add our field errors using a key of the field name  
    $errors['first_name'][] = " First name is required";
}
else if ((!preg_match("/^[a-zA-Z-' ]*$/", $first_name)))
{
    // You can add as many as you need for each field
    $errors['first_name'][] = "Please type in only letters and whitespace";
}
?>
<span class="error">* </span>
First Name: <input type="text" name="first_name" value="<?php if (isset($_POST['first_name'])) {
    echo $_POST['first_name'];
} ?>"/>
<?php
// If we have errors for the field, join them with <br>s
if(array_key_exists('first_name', $errors))
{
?>
    <div class="error">
<?php
    echo implode('<br>', $errors['first_name']);
 ?>
    </div>
<?php
}
?>

Upvotes: 0

Chaska
Chaska

Reputation: 3205

Using elseif means when one field invalid, it will skips other validations. So, simply use if for each validation.

$valid = true;
if (empty($_POST["first_name"])) {
    $first_nameErr = " First name is required";
    $valid = false;
}
if ((!preg_match("/^[a-zA-Z-' ]*$/",$first_name))) {
    $first_nameErr = "Please type in only letters and whitespace";
    $valid = false;
}
if(empty($_POST["last_name"])) {
    $last_nameErr = " Last name is required";
    $valid = false;
}
if ((!preg_match("/^[a-zA-Z-' ]*$/",$last_name))) {
    $last_nameErr = "Please type in only letters and whitespace";
    $valid = false;
}
if (empty($_POST["email"])) {
    $emailErr = "Email is required";
    $valid = false;
}
if (!(filter_var($from, FILTER_VALIDATE_EMAIL))) {
    $emailErr = "Email is invalid";
    $valid = false;
}
if (empty($_POST["message"])) {
    $messageErr = "message is required";
    $valid = false;
}

if ($valid) {
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo '<script>alert("Mail Sent. Thank you , we will contact you shortly.")</script>';
}

Upvotes: 0

Related Questions