CodeIgniter验证错误 - 如何获取key =>的数组价值对?

时间:2012-02-19 10:33:39

标签: php oop codeigniter codeigniter-2

假设一个表单有错误,有没有办法获得一个键数组(字段名称)/值(错误消息)对?例如:

['name'] => 'The name field is required',
['age'] => 'The name must be greater than 18'

如果没有本机方法,我将扩展表单验证库并公开受保护的属性* _error_array *。

2 个答案:

答案 0 :(得分:8)

我最终扩展了核心课程:

class MY_Form_validation extends CI_Form_validation
{
    public function error_array()
    {
        return $this->_error_array;
    }
}

答案 1 :(得分:0)

这可能有点迟了,但是我想分享一个我使用的不涉及扩展CI表单验证库的解决方案。该问题已经有一个可以接受的答案,但我希望它会对其他人有所帮助。

不幸的是,CodeIgniter的$this->form_validation->error_array()方法仅返回源自set_rules()方法的错误。它不考虑生成错误的表单字段的名称。但是,我们可以利用CodeIgniter的另一种方法$this->form_validation->error(),该方法通过将字段名称作为参数传递来返回与特定表单字段相关的错误。

//form validation rules
$this->form_validation->set_rules('f_name', 'First Name', 'trim|required', 
    ['required' => 'First Name is required']
);
$this->form_validation->set_rules('l_name', 'Last Name', 'trim|required', 
    ['required' => 'Last Name is required']
);
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]', 
    [
        'required'      => 'Email is required',
        'valid_email'   => 'Email format is invalid',
        'is_unique'     => 'Email already exists'
    ]
);
$error_arr = []; //array to hold the errors
//array of form field names
$field_names= ['f_name', 'l_name', 'email'];
//Iterate through the form fields to build a field=error associative pair.
foreach ($field_names as $field) {
    $error = $this->form_validation->error($field);
    //field has error?
    if (strlen($error)) $error_arr[$field] = $error;
}

//print_r($error_arr);