HomePHP Page 10 - Building An Extensible Form Validator Class
A Quick Snack - 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.
At this stage, I think I have enough building blocks to actually begin using this class to perform form input validation. Keep in mind, though, that I've been wrong before, and so my initial feeling of satisfaction may soon disappear.
Now, when this form is submitted, the PHP script "processor.php" will take over. This script will first need to verify that the data entered into the form is acceptable (that's where our newly-minted FormValidator class comes in) and then do something with it (for example, INSERT the data into a MySQL database). Take a look:
<?php
// include class
include("FormValidator.class.inc");
// instantiate object
$fv = new FormValidator();
// perform validation
$fv->isEmpty("name", "Please enter a name"); $fv->isNumber("age",
"Please enter a valid age"); $fv->isWithinRange("age", "Please enter an
age within the numeric range 1-99", 1, 99); $fv->isEmpty("sex", "Please
enter your sex"); $fv->isEmpty("stype", "Please select one of the listed
sandwich types"); $fv->isEmpty("sfill", "Please select one or more of
the listed sandwich fillings");
if ($fv->isError())
{
$errors = $fv->getErrorList();
echo "<b>The operation could not be performed because one or
more error(s) occurred.</b> <p> Please resubmit the form after making
the following changes:";
echo "<ul>";
foreach ($errors as $e)
{
echo "<li>" . $e['msg'];
}
echo "</ul>";
}
else
{
// do something useful with the data
echo "Data OK";
}
?>
Let's see if it works. Here's what happens when I submit the
form with no fields filled in:
The operation could not be performed because one or more error(s)
occurred.
Please resubmit the form after making the following changes:
* Please enter a name
* Please enter a valid age
* Please enter an age within the numeric range 1-99
* Please enter your sex
* Please select one of the listed sandwich types
* Please select one or more of the listed sandwich fillings
And here's what happens when I submit the form with incorrect
data in the age field:
The operation could not be performed because one or more error(s)
occurred.
Please resubmit the form after making the following changes:
* Please enter an age within the numeric range 1-99
And here's what happens when I repent, correct all my errors
and submit the form with valid data: