dtcu5885 2012-09-04 14:06
浏览 55
已采纳

如何从check_required_fields函数正确显示错误消息?

Hi i'd like some help please. i'm having a function for validating required fields of forms, in which i pass the req. fields in an array, so if is empty e.g first_name returns an error message: "The first_name is empty." . The problem is that i would like to make the name of the field in the message to look more "friendly" to the user, no camelCases or '_'. How can i achieve this?

p.s. here's my code:

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

Right now the output error message looks like : "The first_name is required" or "The profileInfo is required". The function is this:

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;

}

  • 写回答

1条回答 默认 最新

  • duan198727 2012-09-04 14:11
    关注

    You could give each required field a label...

    $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));
    

    You will need to alter check_required_fields method to handle the $required_fields array correctly, like this:

    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;
    }
    

    Edit: I have just noticed that your loop on $_POST will only work as expected if the fields are set. Try the following:

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀