| Downloaded from www.biorust.com on Wed May 22, 2013 04:24:31 |
![]() | |
| Expandable Form Validation Class : Part 3 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 a long awaited conclusion to this highly received tutorial series, we help wrap up our Form Validation Class.
It is highly recommended that you have read, completed, and fully understood Part 1 and Part 2
of this tutorial series to fully understand what is going on here in this last Part.
Since we will basically be summarizing what we concluded in those Parts and building upon them here, if you have not read them
you will pretty much be in the dark.
In this final Part we will be coding some example validation rules and explaining how to use them. We will then go on and
show how the final complete Class can be applied in a real working environment, so that you can use it in all your future scripts.
At the end of this Part, you should have gained a complete understanding of how the Class operates, and proceed to
expand on it with ease.
A Quick Summary
Here is a quick summary of what we did in Part 1 and Part 2. At the end Part 2, you will remember that
the Class now contains all the major elements to get it to work, which are:
Like I pointed out, the Validation Method is in charge of finding the keywords associated with each form field that instruct the Class how to validate it.
Adding Form Fields is just a way of telling the Class which form fields to validate.
There is one thing missing which I will cover in this Part. And that is the actual validation rules.
If you remember, each keyword is like an actual rule. The rules are in the form of Class Methods, where the name of each Method is the name of each
keyword assigned with _vm added to the start.
To help our Class know what is a keyword and what is the name of each field, the keywords are enclosed in parenthesis, ( ).
eg. a keyword of (Required) will call a Method called _wm_required( ), where the body
of each Method will contain the actual code to validate.
A Simple Validation Example
Let's provide an example on how to create a simple validation rule in the form of a Method to test our Class.
In most web forms, some fields will be required for the user to enter, that is they can not be left blank. This is very simple
to test for. In PHP, we can simply grab the value entered in the form field. If it is empty or NULL string, than nothing was
entered. Therefore an error will be triggered.
Add the following Method to your Class body, which should already contain all the previous code from Part 1 and Part 2. If you get confused, do not worry. At the end of this Part, we will
provide a complete code for everything covered in all 3 Parts.
<?php
function _vm_required( $data , $pos )
{
// Determine If Value Is Set.
if( $data == NULL ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' . ' is Required.';
}
}
?>
This is a validation Method that will be called when a keyword of (Required) is assigned to a form field.
What it does is simply check if there is a value set for the form field. If there is, then the field is not empty, thus
it passes the rule. The check is done with the IF Statement.
The most important thing to note, however, are the two arguments the Method accepts. It is quite important to understand that each
validation Method you create has these two arguments. These arguments are passed automatically by the validate( ) Method in Part 1 of
the tutorial.
$data is the actual form field value entered by the user. $pos is the position of the form field in the form.
How are they used? They are basically a convenience:
$data is used to check the value to validate. Each Validation Method is unique in the way it checks the data passed to it.
In this example's case, we check that $data is not NULL because if it is, that means no value for it was entered, which is what we want to check for.
$pos is used to retrieve the form field's name that is being validated from the array in order to generate our error
message if the $data is indeed NULL.
We save our error messages in a Class Attribute of type array in order to retrieve it and display it later in any way you want.
The form field names are saved in an array called _f_tFName, so by doing this code:
<?php
$this->_f_tFName[ $pos ];
?>
We have basically retrieved the form field's name. Again refer to the validate( ) Method.
Now we have something to work with. To use this Method, obviously to check if a required form fields were
entered or not, all we have to do is add the keyword (Required) to each form field
we want to check. The Class will take care of the rest! Pretty simple.
Where nameOfValidationMethod above will also correspond to the keyword you will add to your form fields.
Second, all validation Methods must accept two arguments in the form of:
You do not have to worry about how to pass values to these arguments. They are done for you automatically. One thing
you do have to worry about, however, is how to actually use them. From the example before, you can pretty much
get an idea but just in case here is a rerun...
You should only use the variable $pos when you want to print the form field's name. You use it as the
key in the $_f_tName array like so:
<?php
$this->_f_tFName[ $pos ];
?>
$data is the actual data that is entered in the form field. You can do whatever check you want on it. For example,
you can compare it to a value, see if it is bigger or smaller than a number, or if its a specific length or not, etc.
Any validation errors (that is error messages you want to print for the user because validation failed for whatever reason), you should
add to the $_l_fError array, like we did in the previous example:
<?php
this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' . ' is Required.';
?>
If you remember in Part 2, we created a Method to easily return an array of error messages for ALL form
fields so that we can display them however we like.
If all of this is still not clear enough, do not worry. It will become more clear when more validation Methods are
presented at the end.
Using The Class
Now that we have a test validation Method and we have explained how to expand on the Class, let's show a visual example
on how the Class can be used in a actual situation. For this example, we will assume the Class source is saved
in an external file which we will
include( )
in our test script.
Let's show some code first than explain each section one at a time.
<?php
// Load Required Libarys.
require_once 'path_to_class_src.php';
/**
* Create Operation Object.
*
* This is the object for our Class that we wil use in our script. The
* Consturctor accepts one argument, which is the form submission method.
* Use 'p' for POST or 'g' for GET.
*/
$vObject = new datVForm( 'p' );
/**
* Validate Form.
*
* The form, if submitted, will be validated. Before the form can be
* validated, the Class must know which form fields to validate
* and their keywords.
*/
/**
* Check If Form Was Submitted.
*
* For a POST form submission Method, all data in the form
* is saved in PHP's $_POST Super Global array. Thus a check
* to make sure it contains any elements will tell us
* if the form was submitted or not.
*/
if( count( $_POST ) > 0 )
{
/**
* Retrive Form Fields.
*
* We save each form field into its own variable
* so we can refrence it easier later in our
* script. Also each form field is trimmed
* to make sure trailing white space
* characters are removed.
*
* Remember that each variable is an actual
* form field, whose name is dertemined
* by the form fields 'name' attribute.
*/
$_POST[ 'Real_Name' ] = trim( $_POST[ 'Real_Name' ] );
$_POST[ 'Email_Address' ] = trim( $_POST[ 'Email_Address' ] );
/**
* Define Validation Rules.
*
* Each form field is validated differently. We define
* how each form field should be validated to the
* Class.
*
* The first argument is the name of our form field
* and the second argument is the keywords. More
* than one keyword is possible but for this example
* we only have one keyword.
*/
$vObject->addFormField( 'Real_Name' , '(Required)' );
$vObject->addFormField( 'Email_Address' , '(Required)' );
/**
* Validate.
*
* We save the BOOL result in a variable. Remember that
* validate( ) returns either TRUE or FALSE based on
* if each form field passed its validation rule.
*/
$fStatus = $vObject->validate( );
}
// Check If Form Was Validated Correctly.
// Errors Encountered.
if( isset( $fStatus ) && ( $fStatus == FALSE ) )
{
echo 'strong>The Following Errors Exist :</strong><br /><br />';
// Get Form Error Messages.
$errorMessages = $vObject->getFormError( );
// Loop And Print Each Error In A List.
// Remember that each element in the
// array is an error message.
echo '<ul>';
for( $i = 0; $i < count( $errorMessages ); $i++ ) {
echo '<li>' . $errorMessages[ $i ] . '</li>';
}
echo '</ul>';
}
else {
// ... Validation Passed. Do Something With Our Script ...
}
// Below Is The Actual HTML for our form. One thing to notice
// is that 'name' attribute for each form field.
?>
<form action="path_to_this_script" id="Test_Form" method="post">
<input name="Real_Name" maxlength="30" size="30" type="text" />
<input name="Email_Address" maxlength="30" size="30" type="text" />
<input name="Button" type="submit" value="Click Me" />
</form>
That is basically how you would use the Class. The comments explain each section but there is one thing to note.
The getFormError( ) Method returns an array of validation errors. I did nothing to format the display of the error messages,
I just printed them into a list. You can pretty much print the error messages anywhere in the HTML you want, even in the HTML code itself.
More Validation Methods
All the examples before assumed that we only had one validation Method to work with. Chances are, there are a limitless number of
ways you may want to validate your form data and to make things easier for you, so we will provide some of them now.
All you have to do is add them to your Class body.
To use them is no different than we provided in Example 5 above. The only difference is the section where we instruct our Class on how
to validate each form field, to which we would add the appropriate keywords:
<?php
$vObject->addFormField( 'Real_Name' , '(Required)(Keyword2)(Keyword3)' );
?>Okay, let's show some more useful validation Methods you can add to your new Class:
<?php
function _vm_pos( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_pos() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] . '</strong>';
return;
}
// Ensure Numeric Characters Are Passed.
if( is_numeric( $data ) == FALSE )
{
$this->_l_sError[] = '_vm_pos() Method : Non Numeric Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] . '</strong>';
return;
}
// Determine If Postive Number And Not Zero.
if( $data <= 0 ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>' . ' must contain a positive number bigger than zero.';
}
}
?><?php
function _vm_pass( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_pass() Method : NULL Data :
Ignore Validation : ' . '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Determine If At Least 8 Characters Exist.
if( strlen( $data ) < 8 ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' .
' must contain at least 8 characters.';
}
// Determine If Alpha-Numeric Characters Exist Only.
$this->_vm_alnum( $data , $pos );
}
?>
<?php
function _vm_numeric( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_numeric() Method : NULL Data : ' .
'Ignore Validation : ' . '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Determine If Numeric Characters Exist Only.
if( is_numeric( $data ) == FALSE ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' .
' must contain Numeric characters only.';
}
}
?>
<?php
function _vm_alnum( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_alnum() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
if( ctype_alnum( $data ) == FALSE ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>' . ' must contain Alpha-Numeric characters only.';
}
}
?>
<?php
class datVForm
{
/**
* Form field names including the keywords.
*
* @var array
*/
var $_f_cFName;
/**
* Form data.
*
* @var array
*/
var $_f_data;
/**
* Form field names without the keywords.
*
* @var array
*/
var $_f_tFName;
/**
* Form method.
*
* @var string
*/
var $_f_type;
/**
* Form validation error messages.
*
* @var array
*/
var $_l_fError;
/**
* Class system error messages.
*
* @var array
*/
var $_l_sError;
////////////////////////////////////////////////////////////
function datVForm( $f_type )
{
// Initialize Class Variables.
$this->_f_cFName = array( );
$this->_f_data = array( );
$this->_f_tFName = array( );
$this->_f_type = $f_type;
$this->_l_fError = array( );
$this->_l_sError = array( );
// Determine Form Method.
if( $this->_f_type == 'p' ) {
$this->_f_data = datLib::string_trim_array( $_POST );
}
else if( $this->_f_type == 'g' ) {
$this->_f_data = datLib::string_trim_array( $_GET );
}
else {
$this->_l_sError[] = 'datVForm() Method : Invalid Form Method ::
Ignore Validation : <em>All Fields</em>';
}
}
////////////////////////////////////////////////////////////
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.
$temp = substr( $this->_f_cFName[ $i ] , $l_nameStart + 1 );
$this->_f_tFName[] = str_replace( '_' , ' ' , $temp );
}
}
////////////////////////////////////////////////////////////
function _vm_alnum( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_alnum() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
if( ctype_alnum( $data ) == FALSE ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' .
' must contain Alpha-Numeric characters only.';
}
}
////////////////////////////////////////////////////////////
function _vm_numeric( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_numeric() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Determine If Numeric Characters Exist Only.
if( is_numeric( $data ) == FALSE ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>' . ' must contain Numeric characters only.';
}
}
////////////////////////////////////////////////////////////
function _vm_pass( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_pass() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Determine If At Least 8 Characters Exist.
if( strlen( $data ) < 8 ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>' . ' must contain at least 8 characters.';
}
// Determine If Alpha-Numeric Characters Exist Only.
$this->_vm_alnum( $data , $pos );
}
////////////////////////////////////////////////////////////
function _vm_pos( $data , $pos )
{
// Ensure Data Is Not NULL.
if( $data == NULL )
{
$this->_l_sError[] = '_vm_pos() Method : NULL Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Ensure Numeric Characters Are Passed.
if( is_numeric( $data ) == FALSE )
{
$this->_l_sError[] = '_vm_pos() Method : Non Numeric Data : Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $pos ] .
'</strong>';
return;
}
// Determine If Postive Number And Not Zero.
if( $data <= 0 ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] . '</strong>' .
' must contain a positive number bigger than zero.';
}
}
////////////////////////////////////////////////////////////
function _vm_required( $data , $pos )
{
// Determine If Value Is Set.
if( $data == NULL ) {
$this->_l_fError[] = '<strong>' . $this->_f_tFName[ $pos ] .
'</strong>' . ' is Required.';
}
}
////////////////////////////////////////////////////////////
function addFormError( $error ) {
$this->_l_fError[] = $error;
}
////////////////////////////////////////////////////////////
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 ) == 0 )
{
$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 : ' .
'Ignore Validation : ' .
'<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 ] );
}
////////////////////////////////////////////////////////////
function getFormError( ) {
return $this->_l_fError;
}
////////////////////////////////////////////////////////////
function getSystemError( ) {
return $this->_l_sError;
}
////////////////////////////////////////////////////////////
function validate( )
{
// Define Local Variables.
$l_dataCount = count( $this->_f_data );
$l_key = array( );
$l_keyCount = NULL;
$l_vm = NULL;
// Find Complete Field Names.
$this->_f_cFName = array_keys( $this->_f_data );
// Find Field Names Without Keywords.
$this->_s_tFName( );
// Loop.
for( $i = 0; $i < $l_dataCount; $i++ )
{
// Determine If Keyword Exists In Field Name.
preg_match_all( '/\((.*?)\)/s' , $this->_f_cFName[ $i ] , $l_key );
// Determine Number Of Keywords, If Any.
$l_keyCount = datLib::array_count_2D( $l_key , 0 );
// Loop.
for( $j = 0; $j < $l_keyCount; $j++ )
{
if( method_exists( $this , '_vm_' . strtolower( $l_key[ 1 ][ $j ] ) ) == TRUE )
{
// Extract Keyword Validation Method.
$l_vm = '_vm_' . strtolower( $l_key[ 1 ][ $j ] );
// Call Validation Method.
$this->$l_vm( $this->_f_data[ $this->_f_cFName[ $i ] ] , $i );
}
else {
$this->_l_sError[] = 'validate() Method : Non Existant Keyword : ' .
'Ignore Validation : ' .
'<strong>' . $this->_f_tFName[ $i ] . '</strong>';
}
}
}
// Return.
if( ( datLib::array_isNull( $this->_l_fError ) == FALSE ) ||
( datLib::array_isNull( $this->_l_sError ) == FALSE ) )
{
return FALSE;
}
/**
* Return TRUE.
*
* The Method will only return TRUE if there are no validation errros.
* Return TRUE means that every field has been validated
* correctly and it is now generally safe to use this form data.
*/
return TRUE;
}
////////////////////////////////////////////////////////////
}
?>