I have the following php form Validation class, which allows me to specify which form inputs are required, the length, and whether the input should be unique.
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = trim($source[$item]);
if($rule === 'required' && empty($value)) {
$this->addError("{$item} is required.");
} else if (!empty($value)) {
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$this->addError("{$rule_value} must match {$item}.");
}
break;
case 'unique':
$check = $this->_db->get('users', array($item, '=', $value));
if($check->count()) {
$this->addError("{$item} is already taken.");
}
break;
}
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
protected function addError($error) {
$this->_errors[] = $error;
}
public function passed() {
return $this->_passed;
}
public function errors() {
return $this->_errors;
}
}
My question is, at the moment the class returns an array of errors which I'm able to foreach through:
foreach($validate->errors() as $error) {
echo $error;
}
but I'm wondering what I can do to allow me to show the errors individually - so I could show the relevant error under the relevant field on the form - as opposed to all as a block at the top.
I hope I've been able to explain that ok!!!