HomePHP Page 9 - Building An Extensible Form Validator Class
Under Construction - PHP
Wondering what OOP can do for you? Well, wonder no more - thisarticle demonstrates how OOP can save you time and effort by building aPHP-based Form Validator object to validate HTML form input. In additionto a detailed walkthrough of the process of constructing a PHP class totest user input, this article also includes usage examples and a brieflook at some powerful open-source alternatives.
So that takes care of the basic validation routines. As you can see, it's fairly easy to add new ones to the class, as per your specific requirements. All that's left now are a couple of methods to access the error list.
The first of these is a simple little method named isError(), which lets you know whether or not any errors have occurred yet. Internally, all this method does is check the size of the $_errorList array; if the size of the array is greater than 1, it implies that one or more errors have occurred while validating the form data. Take a look:
<?php
class FormValidator
{
// snip
// check whether any errors have occurred in validation
// returns Boolean
function isError()
{
if (sizeof($this->_errorList) > 0)
{
return true;
}
else
{
return false;
}
}
}
?>
Of course, all isError() does is tell you whether or not an
error occurred; it won't let you view the list of errors. For that, you need the getErrorList() method, which returns the current $_errorList array.
<?php
class FormValidator
{
// snip
// return the current list of errors
function getErrorList()
{
return $this->_errorList;
}
}
?>
Short and sweet!
Finally, how about resetting the
error list? Well, that's why I have the resetErrorList() method, which clears the $_errorList array of all data.
<?php
class FormValidator
{
// snip
// reset the error list
function resetErrorList()
{
$this->_errorList = array();
}
}
?>
It's a good idea to run this resetErrorList() method whenever
the class is first instantiated - which is why I've added it to the class constructor.
<?php
class FormValidator
{
// snip
// constructor
// reset error list
function FormValidator()
{
$this->resetErrorList();
}
}
?>
In case you didn't already know, PHP makes it possible to
automatically execute a specific function when a new instance of a class is spawned. This function is referred to as a "constructor" and must have the same name as the class. Which, if you look at the code above, is exactly what I've done.