HomePHP Page 11 - Building An Extensible Form Validator Class
Going To The Source - 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.
Of course, this is just my first stab at a generic form validation class. It's designed for very simple requirements, and may be way too primitive for your requirements. If this is the case, you have two basic options:
1. File the results of my efforts in the trash can and write your own, much-cooler, does-everything-but-make-toast class;
2. Pick up a free, open-source PHP class which offers a more powerful feature set.
If you picked door one, you don't really need my help any more. You can stop reading right now and get to work. Have fun, and remember to send me a Christmas card if you sell your software for a million bucks.
If, on the other hand, you're lazy and figured that door two was more promising, you'll be happy to hear that the Web has a huge number of powerful form validation classes floating around it, many of them extremely powerful. Here are two that looked particularly interesting:
Manuel Lemos' form class allows you to programmatically construct HTML forms, offering extremely powerful client- and server-side validation features to make your forms as bulletproof as possible. The class is freely available at http://www.phpclasses.org/browse.html/package/1, and comes with excellent documentation and examples.
Here's an example of a simple online form created with this class:
<html>
<head><basefont face="Arial"></head>
<body>
<?php
// function to output form
// called by class Output() method
function displayForm($str)
{
echo $str;
}
// include class
include("forms.php");
// instantiate object
$contact = new form_class;
// set some form properties
$contact->NAME="contact";
$contact->METHOD="POST";
$contact->ACTION=$PHP_SELF;
// start building the form fields
// add a name field
$contact->AddInput(array(
"TYPE"=>"text",
"NAME"=>"name",
"MAXLENGTH"=>50,
"ValidateAsNotEmpty"=>1, "ValidateAsNotEmptyErrorMessage"=>"You must
enter your name" ));
// note that you can specify how to validate the data while adding a
field // a number of different validation routines are available // look
at the documentation for details
// add an email address field
$contact->AddInput(array(
"TYPE"=>"text",
"NAME"=>"email",
"MAXLENGTH"=>150,
"ValidateAsEmail"=>1,
"ValidateAsEmailErrorMessage"=>"You must enter a valid email address",
));
// add a textarea box for message
$contact->AddInput(array(
"TYPE"=>"textarea",
"NAME"=>"message",
"ROWS"=>6,
"COLS"=>40,
"ValidateAsNotEmpty"=>1, "ValidateAsNotEmptyErrorMessage"=>"You must
enter a message", ));
// and so on
// you can also add radio buttons, list boxes and check boxes
// add a submit button
$contact->AddInput(array(
"TYPE"=>"submit",
"NAME"=>"submit",
"VALUE"=>"Send Message"
));
// check to see if the form has been submitted
// use the form variable "submit" as the key
if ($contact->WasSubmitted("submit"))
{
// if form has been submitted
// read in all the form data
$contact->LoadInputValues(TRUE);
// validate the data on the server-side again
// invalid fields are stored in the array $invalid[]
// the first error message is stored in $error
$error = $contact->Validate(&$invalid);
if ($error != "")
{
// if error, report it
echo "The following error occurred: $error";
}
else
{
// else mail the form data to the webmaster
// and report result
echo "Your message was successfully sent.";
}
}
else
{
// form not yet submitted
// so display it to the user
// begin constructing the form
// using the field definitions above
// note how AddDataPart() can be used to intersperse
// HTML code between the form fields
$contact->AddDataPart("<br> Name: <br>");
$contact->AddInputPart("name");
$contact->AddDataPart("<br> Email address: <br>");
$contact->AddInputPart("email");
$contact->AddDataPart("<br> Message: <br>");
$contact->AddInputPart("message");
$contact->AddDataPart("<br>");
$contact->AddInputPart("submit");
}
// all done
// now output the form/form result
// this function dumps the HTML form (or its result)
// together with all required JavaScript code
$error = $contact->Output(array(
"Function"=>"displayForm",
"EndOfLine"=>"\n"
));
// end
?>
</body>
</html>
As you can see, Lemos' class exposes a number of methods to
dynamically construct form elements, and to apply validation rulesets to them. These form elements can then be printed to the browser, and the data entered into the form can be validated using the built-in client-side and server-side validation functions.
If you're looking for something a little simpler, consider David Tufts' validation class, which provides a an easy-to-use, albeit primitive, form validation API that would probably be best suited to smaller applications. This class is available online at http://dave.imarc.net/php.php
Here's an example of a simple online form created with this class:
<html>
<head>
<basefont face=Arial>
</head>
<body>
<?php
if (!$submit)
{
?>
<form action="<?=$PHP_SELF?>" method="POST">
Name:
<br>
<input type="text" name="name" size="30">
<p>
Email address:
<br>
<input type="text" name="email" size="30">
<p>
Message:
<br>
<textarea name="message" cols="45" rows="6"></textarea>
<p>
<input type="submit" name="submit" value="Send">
</form>
<?php
}
else
{
// include class
include("form_validator.class");
// instantiate object
$fv = new form_validator();
// specify fields to be checked
// these fields are only checked to ensure that they contain
values
// advanced data type validation is not possible
if ($fv->validate_fields("name, email, message"))
{
// if no errors
// send out mail
// report status
echo "Your message was successfully sent.";
}
else
{
// or list errors
echo "The form could not be processed because the
following fields contained invalid data:";
echo "<ul>";
foreach ($fv->error_array as $e)
{
echo "<li>$e";
}
echo "</ul>";
echo "Click <a href=javascript:history.back()>here</a>
to go back and correct the errors";
}
}
?>
</body>
</html>
Short and very sweet - and perfect for applications that
don't require advanced data validation!