
Originally Posted by
EscapeYourMind
I'm using an InputProcessor in which you load rules into it, and each rule can work on multiple form fields when its run, so it would be kind of hard to do it that way since there is no cascade of errors on a single field at a time.
Alternatively, you could feed your validation routine the $_POST array and an array of $rules, which does cascade the errors on a per-field basis.
PHP Code:
$rules = array(
'username' => array(
'name' => 'username',
'label' => 'Your Username',
'maxlength' => 10,
'is_required' => true,
'is_username' => true
),
'password' => array(
'name' => 'password',
'label' => 'Your Password',
'maxlength' => 10,
'is_required' => true,
'is_password' => true
)
);
Your validator could loop through the rules array to see if it finds a matching $_POST var. If it does it checks to see if it is really set (eg, not just spaces, tabs, new lines), and, if so, performs a suite of validation checks relevant to that particular form field back-to-back:
PHP Code:
function validate($_POST, $rules)
{
$errors = array();
foreach ($rules as $key => $rule) {
if (is_really_set($_POST[$key])) {
// do validation
if (!empty($rule['is_username'])) {
if (!is_valid_username($_POST[$key])) {
$errors[$key][] = $rule['label'] . ' is not
a valid username';
}
}
if (!empty($rule['is_password'])) {
if (!is_valid_password($_POST[$key])) {
$errors[$key][] = $rule['label'] . ' is not
a valid password';
}
}
if (!empty($rule['maxlength'])) {
if (!is_valid_maxlength($_POST[$key],
$rule['maxlength'])) {
$errors[$key][] = $rule['label'] . ' can not
exceed ' . $rule['maxlength'] . ' characters';
}
}
} else {
// was it actually required
if (!empty($rule['is_required'])) {
$errors[$key][] = $rule['label'] . ' is required';
}
}
}
return $errors;
}
You could do some other useful things above such as add the $_SESSION['formvars'] array back into the mix.
Bookmarks