The following is a form generator in the vein of Html_Quickform. It'll generate a HTML form and also contains the rules to validate each field and provide you with the validation results.
The idea is that every form field is encapsulated with an object, and each of those objects has a validation rule defining the bounds of the field data. That the actual HTML is encapsulated too just saves on typing out the same thing over and over.
The validation method creates an array keyed by the form field names containing the results of the validation as either true (passed) or false(failed). Error messages can then be displayed based on the array, or in the case of no errors, process the form for whatever purpose.
The code was also my first attempt at Test Led Development. I didn't really follow the paradigm too well (smelly code!) but I really recommend SimpleTest to people interested in this area. TLD really makes you think about your design in the incubating stages of development, and also gives you a safety net when it comes to making changes which possibly have far reaching effects. The set of tests for the classes can be found in the tests folder - you'll need to have SimpleTest installed and in your include_path.
An example form built with this class would be something like this:
$form = new HtmlForm;
$form->setMethod( 'post' );
$form->setAction( '/index.php' );
$form->addField( 'username', new TextField( 'username', '', new SimpleValidationRule( true, '/[a-z]+/', 25 ), 'class="text"'));
$form->addField( 'password', new PasswordField( 'password', '', new PasswordPolicyRule( true, '/[a-z0-9]+/', 12 ), 'class="text"'));
$form->addField( 'submit', new SubmitField( 'submit', 'Submit', new SimpleValidationRule( true, '/[a-z]+/', false ), 'class="submit"'));
if( isset( $_POST['submit'] ))
{
$form->validate();
if( $form->hasErrors() )
{
// Display errors in $form->getErrors();
}
else
{
// Do whatever
}
}
// Display the form
$form->getFormTag();
// PHP 5-only method calling
$form->getField( 'username' )->render();
$form->getField( 'password' )->render();
$form->getField( 'submit' )->render();
$form->getFormCloseTag();