PHP checkField() Function
I wrote a function in PHP that checks submitted form fields for certain requirements. It works by passing in an array of requirements and the array of submitted data such as $_POST or $_GET. The requirements array contains the fields types and names. For example to check for a date field, a name, an email address, and year of birth, you could do this:
$requirements = array(
'date' => 'date',
'text' => 'name',
'email' => 'email',
'date, int, length=4' => 'yearofbirth'
);
$resultArray = checkFields($requirements, $_GET);
It allows you to mix certain types together (where it makes sense) and the function is easy to expand to include new types.
It returns an array. The first key is either true or false depending on how the input validated, and the second key contains an error code and description.
Now with no further delay, here's the code:
/*
$reqs = array(
type => id
'text' => 'name',
'int' => 'year',
'email' => 'email',
'date' => 'date',
'length=2, int, date' => 'month',
'passwordsmatch' => 'password, confirmpass'
);
$input = array | example=($_POST || $_GET)
*/
function checkFields($reqs, $input) {
foreach ($reqs as $type => $id) {
$fields = explode(', ', $id);
foreach ($fields as $field) {
if (!isset($input[$field]) || $input[$field] == '') {
return array(false, $id . ' resulted in err00');
}
}
$types = explode(', ', $type);
foreach ($types as $t) {
switch (preg_replace('|(^.+)(\=.*)|', '$1', $t)) {
case 'passwordsmatch':
$fields = explode(', ', $id);
if ($input[$fields[0]] != $input[$fields[1]]) {
return array(false, $id . ' resulted in err06');
}
break;
case 'date':
if (strtotime($input[$id]) === false) {
return array(false, $id . ' resulted in err05');
}
break;
case 'email':
if (!eregi("^(.+)(@)(.+)(\.)(.+)$", $input[$id])) {
return array(false, $id . ' resulted in err04');
}
break;
case 'length':
// Make sure the field is the correct length
preg_match('|(^.+)(\=)(.*$)|', $t, $m);
if (strlen($input[$id]) != $m[3]) {
return array(false, $id . ' resulted in err01');
}
break;
case 'int':
if (!is_numeric($input[$id])) {
return array(false, $id . ' resulted in err02');
}
break;
case 'text':
if (!is_string($input[$id])) {
return array(false, $id . ' resulted in err03');
}
break;
default:
trigger_error('Invalid type provided to checkFields()', E_USER_ERROR);
}
}
}
return array(true, 'err7 - Success');
}
0 comments:
Post a Comment