CodeIgniter表单验证 - 将结果作为“数组”而不是“字符串”

时间:2009-01-22 05:35:35

标签: php codeigniter

我正在使用CodeIgniter编写表单验证类。有没有办法让我可以在名称值对中获取错误消息?例如,在示例表单中有四个字段:user_namepasswordpassword_conftimezone。其中user_namepassword验证在执行以下操作后失败:

$result = $this->form_validation->run();

如果上面的函数返回false,我想获取名称值对中的错误,如下所示:

Array
{
  'user_name' => 'user name is required',
  'password' => 'passord is required'
}

我真的想形成一个JSON,我可以将其传递给AJAX调用。我有一个(脏)解决方案:我可以逐个调用验证方法,如下所示:

$this->form_validation->required($user_name);
$this->form_validation->required($password);

还有其他方法可以在名称对中获取一次的所有错误消息吗?

编辑:我建议我从其中一个答案中使用jQuery进行验证:

jQuery将有助于客户端验证,但是对于服务器端,我正在使用CodeIgniter验证。

我的设计是为了:

       
  1. 我使用AJAX发布所有值。
  2.    
  3. 在服务器端验证(PHP)。
  4.    
  5. 如果输入有效,则执行所需的操作;否则会向用户返回错误。

7 个答案:

答案 0 :(得分:16)

我通过查看CodeIgniter代码找到了一种方法: 我已经扩展了库CI_Form_validation,如: -

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

我知道,这是一个黑客攻击,但它将满足我对时间的需求。我希望CodeIginter团队能够很快找到一个访问该阵列的接口。

答案 1 :(得分:4)

你可以简单地使用,

$this->form_validation->error_array();

这是来自CodeIgniter的class reference documentation

答案 2 :(得分:1)

看到代码点火器验证会在正常页面刷新时给出错误消息,使用像jquery validation plugin之类的东西会不会更好,它会在发送表单之前完全验证客户端?这种方式不需要AJAX。

编辑: 我不是建议不要进行服务器端验证,只是为了验证而使用AJAX发布是没有必要的,如果你在客户端这样做会减少服务器命中率。它会优雅地降级为常规页面刷新,错误或成功消息。

答案 3 :(得分:1)

我最喜欢的解决方案不涉及在任何地方添加功能或扩展验证库:

$validator =& _get_validation_object();
$error_messages = $validator->_error_array;

参考:http://thesimplesynthesis.com/post/how-to-get-form-validation-errors-as-an-array-in-codeigniter/

您应该可以在代码中的任何位置调用它。此外,值得注意的还有一个newer thread也可以讨论这个问题。

答案 4 :(得分:1)

您可以在控制器中创建私人功能

    private function return_form_validation_error($input)
{
    $output = array();
    foreach ($input as $key => $value)
    {
        $output[$key] = form_error($key);
    }
    return $output;
}

然后在你的验证方法中,只需调用它,这是我的

public function add_cat_form()
    {
        $this->output->unset_template();
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run())
        {
            if (IS_AJAX)
            {
                $dataForInsert = $this->input->post();
                if ($dataForInsert['parentid'] == -1)
                {
                    unset($dataForInsert['parentid']);
                }
                $this->post_model->add_cat($dataForInsert);
                echo json_encode('success');
            } else
            {
                #in case of not using AJAX, the AJAX const defined
            }
        } else
        {
            if (IS_AJAX)
            {
                #This will be return form_validation error in an array
                $output = $this->return_form_validation_error($this->input->post());
                echo $output = json_encode($output);
            } else
            {
                #in case of not using AJAX, the AJAX const defined
            }
        }
    }

答案 5 :(得分:0)

已经有一个正确的答案,但是我认为这对于如何执行该过程更容易理解。

在您的 Controller

中执行
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
    $data['error'] = validation_errors();
}else{
  //success
}
echo json_encode($data);

使用您的 JS

success:function(response){
 if(response.error){
  $('#notif').html(response.error); 
 }else{
   //do stuff here...
 }
}

最后显示与您的js中给定ID相对应的错误。

使用您的 HTML

<span id="notif"></span>

答案 6 :(得分:0)

这可能是迟来的,但我想分享我曾经希望能使其他人受益的解决方案。

不幸的是,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);