Simplifying PHP Form Processors (Part II)
I've been thinking quite a bit more on the subject of Simplifying PHP Form Processors. I think it would be important for the community to come up with a solution to the problem. The form processor, which I'm busy working on at the moment currently looks like (utilising bits and pieces of code I've developed over the past couple of years):
<?php
/**
* @author Jacques Marneweck <jacques@php.net>
* @copyright 2002-2005 Jacques Marneweck. All rights reserved.
* @version $Id$
*/
Class FormValidator {
var $errors = array ();
var $fields = array ();
/**
* Generate a signature for form data to verify that the data has not
* changed
*
* @param mixed data
* @return string sha1 hash of serialized data
* @access public
*/
function signature ($data) {
$ctx = sha1(serialize($data));
return ($ctx);
}
/**
* Check a required field is filled out
*
* @param array required fields
* @param array post data
* @return array errors
* @access public
*/
function checkrequired ($required, $data) {
foreach ($required as $field => $reason) {
if (!isset($data[$field]) || empty($data[$field])) {
$this->errors[] = $reason;
$this->fields[] = $field;
}
}
}
/**
* Retrieve an array of error messages
*
* @return array array of error messages
* @access public
*/
function geterrors () {
return ($this->errors);
}
/**
* Retrieve an array of fields that have missing / invalid data
*
* @return array array of fields
* @access public
*/
function getfields () {
return ($this->fields);
}
/**
* Check if the form has errors
*
* @return bool true if has errors else false
* @access public
*/
function haserrors () {
if (sizeof($this->errors) > 0) {
return true;
} else {
return false;
}
}
/**
* Check if a form has successfully validated and does not have
* errors
*
* @return bool true if valid else false
* @access public
*/
function isValid () {
if (sizeof($this->errors) === 0) {
return true;
} else {
return false;
}
}
};
There are various things which need to be taken into consideration, which I've been thinking about quite a bit lately which affect various people involved in the normal development process:
- Making it easier from a presentation point-of-view to allow designers to allow say changing the row background to red for a row where there is an error, to displaying say a red exclaimation mark, displaying a error message below / above the field
- a better way for rule processing first checking if the field is compulsory, and then going through the rest of the ruleset checking if there is more errors rather than saying that you need to enter a new password and password confirmation does not match, etc.
- allowing developers to control the rulesets that are required per the specifications document rather than leaving it in the web designers hands to change without anyone noticing / reading the web designers commit messages.