Downloaded from www.biorust.com on Wed Feb 08, 2012 04:33:34

 
Expandable Form Validation Class : Part 2
Tutorial Author - Limitless (http://www.llstudios.net)

IMPORTANT: This tutorial (and other component parts) make use of the datLib library, which you can download here. The author has stopped working on this project, but you can check out their website for similar up-to-date libraries.

In Part 1 of this tutorial, we covered the basics of our Form Validation Class.  We explained how the core of the Class depends on regular expressions and gave an insight regarding the keyword concept. We also explained how each keyword will have a corresponding Class Method so that we can easily extend the Class in the future to suit our needs.

In Part 2, we will get our hands dirty in creating the remaining useful Class Methods that will instruct the Class which form fields to validate and how to validate them.

In comparison to Part 1, this Part is significantly shorter, easier, and to the point.


Adding Fields To Be Validated
To use our Class in a development environment, we must somehow provide a way for the programmer to instruct the Class which form fields to validate upon submission.

This will be done via a new Class Method we will now create called addFormField( ).


The addFormField( ) Method
Our Method will accept two arguments, the name of the form field and the keywords for it. Let's look at the code and then explain each section.


<?php

    
function addFormField$fName $keyword )
    {
        
/**
         * Check If Form Is Sent.
         *
         * If the form is not sent, an error will always be triggered

         * because the Class will assume no form field exists.
         */
        
if( count$this->_f_data ) == )
        {
         
$this->_l_sError[] =    'addFormField()       Method : No Form Data : Ignore Add Field : ' .
                                 
'<strong>' $fName '</strong>';
            return;
        }

        
/**
         * Determine If Form Field Name Exists.
         * Adding a form field to the array is only done

         * if the form field exists. This is to avoid any
         * possible errors in the validation
         * process from occuring on a non existant field.
         * If a form field does not exist, a system error is triggered.
         */
        
if( array_key_exists$fName $this->_f_data ) == FALSE )
        {
         
$this->_l_sError[] =    'addFormField() Method : Non Existant Form Field : ' .
                                 
'<strong>' $fName '</strong>';
            return;
        }

        
// Add Keywords.

        
$this->_f_data$keyword $fName ] = $this->_f_data$fName ];

        
// Remove Form Field Name Without Keywords.

        
unset( $this->_f_data$fName ] );
    }

?>

In Part 1, we explained that all form data sent by PHP is either saved in a $POST or $GET Super Global. To make life easier for us, we save this data in a Class Attribute depending on the form method so we do not always have to check both Super Global's.

We want to add some sort of error check to our Class, to avoid adding non existent fields. This is to ensure that our Class will run at the fastest possible speeds. If non existent fields are allowed to be added, not only will PHP parser warning be generated, but our Class will loop through an endless number of form fields that simply do not exist.


<?php

        
if( count$this->_f_data ) == )
        {
            
$this->_l_sError[] =    'addFormField() Method : No Form Data : Ignore Add Field : ' .
                                    
'<strong>' $fName '</strong>';
            return;
        }

?>

In the above code segment, we make sure the form was submitted, there hence making sure that there is some sort of form data to work with. Technically we can skip the top step, since the next code segment also does some sort of error check, but leaving it won't hurt.


<?php

        
if( array_key_exists$fName $this->_f_data ) == FALSE )
        {
            
$this->_l_sError[] =    'addFormField() Method : Non Existant Form Field : ' .
                                    
'<strong>' $fName '</strong>';
            return;
        }

?>

Again here we make use of the PHP function array_key_exists( ). If you remember from Part 1, we said that the array housing our form data has as keys each form field name.

So by checking that there is a key with our form field name that we wish to add does indeed exist in our array, we make sure that we are not adding a non existent field. The above code segment returns a Class system error message if the key does not exist.

Having made sure that no errors will be encountered when adding a new field, we then proceed to add a new field to our array, with the keywords included. This is a two step process.

First we add to our array a new key with a value of the keywords followed by the field name. Then we remove the old key to avoid any errors.

What does this mean? Well, let's say in our array we had a key of Email and we wanted to add a keyword of (Required). We will create a new key in our array called (Required)Email then remove the old key of Email alone. This is exactly what we have done in the code below.


<?php

        
// Add Keywords.

        
$this->_f_data$keyword $fName ] = $this->_f_data$fName ];

        
// Remove Form Field Name Without Keywords.

        
unset( $this->_f_data$fName ] );

?>

A Little Explaining
Some people might argue that this way of adding form fields with keywords is not the best method. They state that another array could be created to house all keywords relevant to each form field. Then simply in the validation process, each array can be called for each form field to determine how to validate.

I disagree with this method for several reasons. First, this Class is designed to be fast an non memory intensive. Creating another array will just eat up more memory, especially if your form gets large enough. Imagine a multi page form with 30 fields, some of which have multiple selections such as check boxes and radio buttons.

To create a second array housing all possible keywords will mean an average of one key for each choice. Then to link that array with each form field will take a little extra processing when validation; we would have to loop through each form field to find its associated keyword, then loop through it again to validate each keyword.

If you remember our validate( ) Method from Part 1, this would mean 2 extra nested loops, brining the grand total to 4. Indeed a lot of extra unnecessary overhead.

Even if we are using Regular Expressions, because our form field names are short, will usually be no larger than 25 characters, the pattern to match is faster than all the overhead suggested above combined.

One array is simple code wise and much faster and more convenient.

 

Form Field Names Without Keywords
Because we want to display our form field names next to the generated error messages without the keywords included, we have a special Method that does so, which you will remember from Part 1. Let's see some code:


<?php

function _s_tFName( )
{
    
// Define Local Variables.

    
$l_dataCount    count$this->_f_data );
    
$l_nameStart    NULL;

    
// Loop.

    
for( $i 0$i $l_dataCount$i++ )
    {
        
// Find Last ')' Character In Field Name.

        
$l_nameStart strrpos$this->_f_cFName$i ] , ')' );

        
// Extract Field Name Without Keyword.

        
$this->_f_tFName[] = str_replace'_' ' ' substr$this->_f_cFName$i ] , $l_nameStart ) );
    }
}

?>

We loop through each form field finding the last closing parenthesis. If you remember from Part 1, our keywords are housed in ( ) and they precede the form field name. So by finding the last closing parenthesis, ), and extracting all characters after it, we get the form field name alone.


<?php

// Extract Field Name Without Keyword.

$this->_f_tFName[] = str_replace'_' ' ' substr$this->_f_cFName$i ] , $l_nameStart ) );

?>

Why are we using the str_replace( ) function? For form field names with a space character, " " included in it, PHP by default adds a _ where the space character is. That just looks plain ugly, so we simply remove the _ from the form field name when extracting it.

 

Returning Error Messages
We need to provide a way to return both form and system error messages. This is better than simply printing them because they can be passed as arguments to a format function, or be used anywhere in the code to be displayed where the user want them to be in the HTML layout. The code is pretty simple to understand and requires no further explaining.


<?php

    
function getFormError( ) {
        return 
$this->_l_fError;
    }

    
///////////////////////////
    
function getSystemError( ) {
        return 
$this->_l_sError;
    }

?>



Conclusion
In Part 2 here we covered how the Class can be used by the programmer and created several Class Methods to explain how to instruct the Class which form fields to validate as well as supported the methods we used.

In Part 3, we will create several validation Methods and take the Class on a test run to see how it works and how it can be used directly in a project.

A couple of closing notes; all our support was tested in actual environments and while the execution speed of PHP scripts will vary depending on the version used, server traffic, and connection speed, the results were pretty accurate over several tests. While this Class can be done in many different ways, we are happy with ours and we invite you, dear reader, to experiment and try other methods. After all the code is only as good as the programmer and we in no means are saying we gods. I am sure someone out there that is better than us can come up with a different method




All Content © BioRUST 2012 All Rights Reserved.