Posted: Fri Aug 04, 2006 1:21 am
How's this looking?
Form.inc.php
Formfield.inc.php
Usage:
Form.inc.php
Code: Select all
<?php
require('FormField.inc.php');
class Form{
private
$fields = array(),
$rules = array(),
$filters = array(),
$errors = array();
public function __construct(){
}
public function addField(FormField $field){
$name = $field->getName();
$this->fields[$name] = $field;
}
public function addRule($rule){
$this->rules[] = $rule;
}
public function addFilter($filter){
//TODO I might use this later, I don't know
$this->filters[] = $filter;
}
public function validate(){
foreach($this->rules as $rule){
$rule->check() or $this->errors['form'][] = $rule->getError();
}
foreach($this->fields as $field){
$field->validate() or $this->errors[$field->getName()] = $field->getErrors();
}
return empty($this->errors);
}
public function getErrors(){
return $this->errors;
}
}
?>Code: Select all
<?php
class FormField{
private
$name, // Name of field
$value, // Value of field
$filters = array(), // Array of filter (objects) to be performed on value before validation
$rules = array(), // Array of validation rules (objects) to be checked before validation
$errors = array(); // Array of corresponding errors to output to the user
public function __construct($name, $value){
$this->name = $name;
$this->value = $value;
}
public function addRule($rule){
$this->rules[] = $rule;
}
public function addFilter($filter){
$this->filters[] = $filter;
}
public function validate(){
foreach($this->filters as $filter){
$this->value = $filter->run($this->value);
}
foreach($this->rules as $rule){
$rule->check($this->value) or $this->errors[] = $rule->getError();
}
return !$this->getErrors();
}
public function getName(){
return $this->name;
}
public function getValue(){
return $this->value;
}
public function getErrors(){
return $this->errors;
}
}
?>Code: Select all
<?php
$Registry->register('Form', null, $request->getData());
$Form = $Registry->get('Form');
$title = new FormField('title', $request->get('title'));
$title->addRule(new RuleRange($title_max_length, 1, 'Must be between 1 and ' . $title_max_length . ' characters in length.'));
$body = new FormField('body', $request->get('body'));
$body->addRule(new RuleRange($body_max_length, 1, 'Must be between 1 and ' . $body_max_length . ' characters in length.'));
$Form->addField($title);
$Form->addField($body);
$Form->addRule(new RuleMatch(array($request->get('title'), $request->get('body')), 'Title must match body'));
if($Form->validate()){
echo "Valid Form Submission. ";
}
else{
$errors = $Form->getErrors();
print_r($errors);
}
?>