data = $data; } } private function setError($error) { $this->errors[] = $error; } public function getErrors() { return $this->errors; } public function getUniqueErrors() { return array_unique($this->errors); } public function isValid() { return sizeof($this->errors) < 1 ? true : false; } public function addRule($fields, $rule, $message) { if (array_key_exists($fields, $this->data)) { if ($rule instanceof iRule) { $this->validation = $rule; if (!$this->validation->check($this->data[$fields])) { $this->setError($message); } } } } } interface iRule { public function check($word); } class RuleLength implements iRule { private $rules = array(); public function __construct($minimum) { $this->rules['min'] = $minimum; } public function check($word) { $size = strlen($word); return ($size >= $this->rules['min']) ? true : false; } } /* * Checks if the word is set or not */ class RuleRequired implements iRule { public function __construct() {} public function check($word) { $size = strlen($word); return ($size > 0) ? true : false; } } class RuleRegex implements iRule { private $rules = array(); public function __construct($pattern) { $this->rules['pattern'] = $pattern; } public function check($word) { return (preg_match($this->rules['pattern'], $word) != 0); } } if (isset($_POST['send'])) { $val = new Validator($_POST); $val->addRule('username', new RuleRequired(), 'Empty field!'); $ruleRequired = array( 'username' => 'Username left empty!', 'age' => 'Age is empty', 'school' => 'School textbox is empty!' ); foreach ($ruleRequired as $key => $value) { $val->addRule($key, new RuleRequired(), $value); } $ruleRequired = array( 'username' => array(new RuleRegex('(^[0-9]+$)'), 'Username must be numbers!'), 'age' => array(new RuleRegex('(^[0-9]+$)'), 'Age must be only numbers!'), 'school' => array(new RuleRegex('(^[A-Z]+$)'), 'School must be caps on!') ); foreach ($ruleRequired as $key => $value) { $val->addRule($key, $value[0], $value[1]); } if ($val->isValid()) { echo 'It is OK'; } else { foreach ($val->getUniqueErrors() as $value) { echo "$value
"; } } } ?>
username :
age:
school: