这个简单的脚本理论上应该检查表单是否有错误,然后打印它发现的任何错误。
formValidate 函数接受一个表单数组,表单中的每个字段都有一个经过验证的值。该字段还有一个错误键,其值为空数组。我正在尝试将我发现的任何错误附加到特定字段的错误数组中。然后我在完成后返回表单数组。
我稍后打印出所有字段的错误。不幸的是,错误从未出现。
我已经为此烦恼了好几个小时,我一生都无法弄清楚为什么我的脚本中的表单错误没有被应用。
任何帮助将不胜感激!
# get value from array
function array_get(array $array, $key, $default = null)
{
return (array_key_exists($key, $array)) ? $array[$key] : $default;
}
# get string value from array
function array_get_string(array $array, $key, $default = '', $trim = true)
{
$val = array_get($array, $key);
if (is_string($val)) {
return ($trim) ? trim($val) : $val;
}
return $default;
}
function validateForm($form)
{
// validateField each field
foreach ($form as $field)
{
foreach ($field['validation'] as $validate)
{
switch($validate)
{
case 'email':
if(!filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {
$field['errors'][] = $field['value'] . ' is an invalid email address.';
}
break;
case 'number':
if(!preg_match('/^[0-9 ]+$/', $field['value'])) {
$field['errors'][] = $field['value'] . ' is an invalid number.';
}
break;
case 'alpha':
if(!preg_match('/^[a-zA-Z ]+$/', $field['value'])) {
$field['errors'][] = $field['value'] . ' contains invalid characters. This field only accepts letters and spaces.';
}
break;
}
}
}
return $form;
}
// $post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$post = $_POST;
$ajax = array_get_string($post, "request_method") == 'ajax';
# select data that needs validation
$form = array(
'fullname' => array(
'value' => array_get_string($post, "full-name"),
'validation' => array('alpha', 'required'),
'errors' => array(),
),
'emailaddress' => array(
'value' => array_get_string($post, "email-address"),
'validation' => array('email'),
'errors' => array(),
),
'activites' => array(
'value' => array_get_string($post, "activites"),
'validation' => array('default'),
'errors' => array(),
),
'country' => array(
'value' => array_get_string($post, "country"),
'validation' => array('default'),
'errors' => array(),
),
'contactpreference' => array(
'value' => array_get_string($post, "contact-preference"),
'validation' => array('default'),
'errors' => array(),
),
'message' => array(
'value' => array_get_string($post, "message"),
'validation' => array('alpha'),
'errors' => array(),
),
);
// validate the form
$form = validateForm($form);
foreach ($form as $field)
{
foreach ($field['errors'] as $error)
{
echo $error . '<br />';
}
}