0

嗨,我需要一些帮助。我有一个功能来验证表单的必填字段,我在其中传递了 req. 数组中的字段,因此如果为空,例如 first_name 返回错误消息:“First_name 为空。” . 问题是我想让消息中的字段名称看起来对用户更“友好”,没有驼峰或“_”。我怎样才能做到这一点?

ps这是我的代码:

$required_fields = array('first_name', 'last_name', 'email', 'profileInfo', 'message');
$errors = array_merge($errors, check_required_fields($required_fields));

现在,输出错误消息看起来像:“需要名字”或“需要 profileInfo”。功能是这样的:

function check_required_fields($required_fields) {
$field_errors = array();
foreach($_POST as $field=>$value){
    if(empty($value) && in_array($field, $required_fields) === true){
        $field_errors[] = "the " . $field . " is required.";
        //break 1;
    }
}
return $field_errors;

}

4

1 回答 1

2

您可以给每个必填字段一个标签...

$required_fields = array(
        'first_name' => 'First Name',
        'last_name' => 'Last name',
        'email' => 'Email Address',
        'profileInfo' => 'Profile information',
        'message' => 'Message'
    );
$errors = array_merge($errors, check_required_fields($required_fields));

您将需要更改check_required_fields方法以$required_fields正确处理数组,如下所示:

function check_required_fields($required_fields)
{
    $field_errors = array();
    foreach ($_POST as $field => $value)
    {
        if (empty($value) && array_key_exists($field, $required_fields) === true)
        {
            $field_errors[] = "the " . $required_fields[$field] . " is required.";
            //break 1;
        }
    }
    return $field_errors;
}

编辑:我刚刚注意到,$_POST如果设置了字段,您的循环只会按预期工作。尝试以下操作:

function check_required_fields($required_fields)
{
    $field_errors = array();
    foreach ($required_fields as $field => $label)
    {
        $value = $_POST[$field];

        if (empty($value))
        {
            $field_errors[] = "the " . $label . " is required.";
            //break 1;
        }
    }
    return $field_errors;
}
于 2012-09-04T14:11:10.820 回答