Tuesday, May 21, 2013

How to Validate a Form Using PHP Part 2: Streamline Using Arrays


How to Validate a Form Using PHP Part 2: Streamline Using Arrays

We’ve touched upon the basic elements of form validation and error messages in part 1 of this series, which outlines a relatively static method identifying errors and validating a form. In this edition we are going to make the elements we began with more dynamic and reduce the amount of script required to do so using arrays.

Setting Up the Form

First we’re going to want to create a form on a new .php document, mine is going to be called errorpart2.php. Below is my form complete with fields name, email, and comments.
  1. <form id="commentform" method="post" action="errorpart2.php">  
  2.     <p>  
  3.     <label for="name">Name:</label>  
  4.     <br/>  
  5.     <input name="name" id="name" type="text"/>  
  6.     </p>  
  7.     <p>  
  8.     <label for="email">Email:</label> <br/>  
  9.     <input name="email" id="email" type="text"/>  
  10.     </p>  
  11.     <p>  
  12.     <label for="comments">Comment:</label>  
  13.     <br/>  
  14.     <textarea name="comments" id="comments" rows="4"></textarea>  
  15.     </p>  
  16.     <p>  
  17.     <input name="submit" id="submit" type="submit" value="Submit" />  
  18.     </p>  
  19. </form>  
The next step is to put in place a check to see if the form is submitted, so the script knows to validate. For those that have read part 1 of this series I had used a hidden input to pass this check, I have since done some additional research on the matter and found an alternative more secure method.
  1. if (array_key_exists('submit',$_POST)){  
  2. //Form has been submitted  
  3. }  
This method checks the $_POST array for the key ‘submit’, which is the array key for our Submit button, and would only be present if the form was submitted. We will be placing all of our validation related script within this IF statement, ensuring it only runs when required.

Laying Down Array Groundwork

We will need to define the arrays we will be using for this script, one containing all the field names on the form, one with all the mandatory fields, and one to store any errors we come across.
  1.     // Fields that are on form  
  2.     $expected = array('name''email''comments');  
  3.     // Set required fields  
  4.     $required = array('name''comments');  
  5.     // Initialize array for errors  
  6.     $errors = array();  
The $expected array serves to identify and process all  fields, mandatory or not. It also ensures that only the fields you specify are processed and prevents security issues from rogue $_POST values.

Making It Dynamic

The next part is where a big benefit of using arrays comes into play. Instead of typing out IF statements for each $_POST field, we can make use of the foreach statement to do this dynamically.
  1. foreach ($_POST as $field => $value){  
  2.     // Make sure field was done correctly otherwise add error.  
  3. }  
This snippet goes through each key and the corresponding value that the $_POST array holds. This means that each field submitted will be processed, which is especially useful when dealing with long forms.
From within this foreach we now want to do two things to each variable passed through it..
1. Clean up the variable by eliminating whitespace if it is not an array. I used shorthand for this conditional statement:
  1. // Assign to $temp and trim spaces if not array  
  2. $temp = is_array($value) ? $value : trim($value);  
2. If field is empty then make sure it is not required, otherwise add related error message to the $error array. For those unfamiliar with array_push, it can be used to append additional values into an existing array, in this case the one we defined before:
  1. // If field is empty and required, tag onto $errors array  
  2. if (empty($temp) && in_array($field, $required)) {  
  3.       array_push($errors, $field);  
  4.   
  5. }  
Once these two steps are in place, we have finished the foreach statement.

Handling the Errors

Now that we have the $error array with the names of each required field not filled out, we need to either accept the form or show the error messages.
If the form is done correctly:
  1. if (empty($errors)){  
  2.         //The form is completed properly to do with as you please  
  3.         unset($errors);  
  4. }  
The unset(); function destroys the $errors array, so it does not cause incorrect error messages to be displayed.
To display error messages I placed the following lines of code next to the corresponding labels, only appearing when applicable:
  1. <?php if (isset($errors) && in_array('name'$errors)){?>  
  2. <div class="red">Please enter name</div>  
  3. <?php } ?>  
This checks the $errors array for the specified field name , in this case ‘name’, which would only be present if an error happened. The same lines must be placed next to each field you are displaying an error for. I included the error message with my CSS styles applied, they can be found in the complete script at the bottom of this page.

Prevent Inputs from Clearing After an Error

When a user submits the form after completing some of the mandatory fields but not all, they would currently be shown an error message and the form would be cleared. This is a frustrating usability problem that can drive users away. Luckily, now that we have implemented array based validation, it is also easy to fix.
This line of code checks if there are any errors and, if there are, it inserts value = “” containing the user input submitted. This puts the value of the input to whatever the user had it as prior to the error, so they don’t have to retype anything. It is important to enclose this echo statement in literal ‘ ‘ quotes as well as wrap the $_POST[] in htmlentities. To ensure quotes and other symbols inputted do not break your page htmlentities converts some symbols to their HTML equivalent (example:  ” to &quot; ).
  1. <input name="name" id="name" type="text"  
  2.     <?php if (isset($errors)) { echo 'value="'.htmlentities($_POST['name']).'"'; } ?>  
  3. />  
The above will work for inputs, but the following tweak must be done to accommodate a textarea:
  1. <textarea name="comments" id="comments" rows="4"><?php  
  2.     if (isset($errors)) { echo htmlentities($_POST['comments']); }  
  3. ?></textarea>  
It is important to note that in order to avoid white space, make the <?php tags touch the textarea tags.

0 comments:

Post a Comment

    Blogger news

    Blogroll

    About