Tuesday, May 21, 2013

How to Validate a Form Using PHP Part 1: Complete with Error Messages!


How to Validate a Form Using PHP Part 1: Complete with Error Messages!

Having a site visitor fill out a form is the primary way to gather information. Forms are the main line of communication with anyone that visits your site, so taking the time to make sure users fill them out correctly is key. Using PHP, we are able to ensure that all fields are properly filled out before submission, with required adjustments being called to attention through the use of error messages.

The CSS & HTML Groundwork

Let’s start off by opening up a fresh php document and putting a form within it. I have created errorpart1.php
  1. <html>  
  2.     <head>  
  3.         <title>Form validation using PHP</title>  
  4.         <style type="text/css"><!--Styles--></style>  
  5.     </head>  
  6.     <body>  
  7.         <div id="content">  
  8.            <!--PHP and Form to go here-->  
  9.         </div>  
  10.     </body>  
  11. </html>  
With the following styles applied to the form:
  1. *{  
  2.     padding:0px;  
  3.     margin:0px;  
  4. }  
  5. body{  
  6.     text-align:center;  
  7.     font:11px "Lucida Grande",Arial,sans-serif;  
  8. }  
  9. #content{  
  10.     width:300px;  
  11.     text-align:left;  
  12.     margin:10px;  
  13. }  
  14. .formitem{  
  15.     width:100%;  
  16.     padding6px;  
  17.     font:11px "Lucida Grande",Arial,sans-serif;  
  18. }  
  19. h2{  
  20.     font:18px "Helvetica",Arial,sans-serif;  
  21. }  
  22. .box{  
  23.     width:100%;  
  24.     padding:10px 0px 10px 5px;  
  25.     margin-bottom8px;  
  26.     font-weight:bold;  
  27. }  
  28. .green{  
  29.     background-color:#95ca78;  
  30.     border-bottom:solid 1px #8AA000;  
  31. }  
  32. .red{  
  33.     background-color:#FDCBCA;  
  34.     border-bottom:solid 1px #E8514A;  
  35. }  
Next we have to construct our form, I have chosen to create a three field form, including one hidden field entitled “submitted”, which serves to check if the form has been completed.
  1. <form action="index.php" method="POST" enctype="multipart/form-data">  
  2.     <h2>Title</h2>  
  3.     <input class="formitem" type="text" name="title"/>  
  4.     <br/><br/>  
  5.     <h2>Content</h2>  
  6.     <textarea class="formitem" name ="textentry" rows="3"></textarea>  
  7.     <input type="hidden" name="submitted" value="1">  
  8.     <br/><br/>  
  9.     <input type="submit" value="Submit"/>  
  10. </form>  
Now that we’ve laid out and styled up our page, it’s time to come in with some PHP.

The PHP and Validation

First we’ll use the hidden field (“submitted”) that we created earlier to check if the form is ready to be validated aka if they submitted it. We can do this with a simple IF statement, checking to see if submitted has a value of “1″, which it it automatically set to on form submission. This prevents error messages from popping up unless the form was actually completed and turned in.
  1. <?php  
  2. //If form was submitted  
  3. if ($_POST['submitted']==1) {  
  4.    //Do something  
  5. }  
  6. ?>  
Next up we have to check each mandatory field for a value of some kind. I have decided that both the title and content fields are mandatory for this example. The below code checks for values in each field on the form and assigns them to a variable if they exist.
  1. <?php  
  2. //If form was submitted  
  3. if ($_POST['submitted']==1) {  
  4.     if ($_POST[title]){  
  5.         $title = $_POST[title]; //If title was entered  
  6.     }  
  7.     if ($_POST[textentry]){  
  8.         $textentry = $_POST[textentry]; //If comment was entered  
  9.     }  
  10. }  
Now that we have put the values retrieved from the form into variables, we can perform a check to see if any are blank. If they have all been filled out properly, a message alerts them they completed the form properly.
  1. //If all fields present  
  2. if ($title && $textentry){  
  3.     //Do something  
  4.     echo "<div class=\"box green\">Form completed!</div>";  
  5. }  
  6. ?>  
Now for those of you that are currently questioning why I didn’t combine the last two parts into one big IF statement, hold on, it’s error message time.

At this point in the game, we want to go back to where we first assigned the $_POST variables to strings variables, appending an else to each IF statement.
  1. if ($_POST['submitted']==1) {  
  2.     $errormsg = ""//Initialize errors  
  3.     if ($_POST[title]){  
  4.         $title = $_POST[title]; //If title was entered  
  5.     }  
  6.     else{  
  7.         $errormsg = "Please enter title";  
  8.     }  
  9.     if ($_POST[textentry]){  
  10.         $textentry = $_POST[textentry]; //If comment was entered  
  11.     }  
  12.     else{  
  13.         if ($errormsg){ //If there is already an error, add next error  
  14.             $errormsg = $errormsg . " & content";  
  15.         }else{  
  16.             $errormsg = "Please enter content";  
  17.         }  
  18.     }  
  19. }  
That last section might have seemed like a lot, so let’s break it down.
First off we established the variable $errormsg, which will contain a string with all the errors we come across.
  1. $errormsg = ""//Initialize errors  
Next we append the first IF statement for the title field, stating that if there is no value, set the $errormsg to store that error.
  1. else{  
  2.     $errormsg = "Please enter title";  
  3. }  
When we check the next field, textentry, we will essentially be doing the same thing, although this time we must check if $errormsg has any errors stored from the previous IF. Should this be the case, we must append our current error message to the previous one.
  1. else{  
  2.     if ($errormsg){ //If there is already an error, add next error  
  3.          $errormsg = $errormsg . " & content";  
  4.     }else{  
  5.          $errormsg = "Please enter content";  
  6.     }  
  7. }  
At this point your $errormsg variable should have an accurate list of error messages stored. Now it is time to alert the user of any problems.
  1. if ($errormsg){ //If any errors display them  
  2.     echo "<div class=\"box red\">$errormsg</div>";  
  3. }  

0 comments:

Post a Comment

    Blogger news

    Blogroll

    About