You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter控制器中获取表单验证错误(API开发场景)

CodeIgniter控制器获取验证错误信息的方法

针对不同版本的CodeIgniter,获取验证错误信息的方式略有差异,以下是API开发场景下的具体实现:

CodeIgniter 3

  • 加载表单验证库后执行验证逻辑,验证失败时,使用$this->form_validation->error_array()获取数组格式的错误信息,适合直接转为JSON返回给前端。
  • 若需字符串格式的错误信息,可使用$this->form_validation->error_string(),但API场景更推荐数组格式。

示例代码:

public function submit_api()
{
    $this->load->library('form_validation');
    
    // 设置验证规则
    $this->form_validation->set_rules('email', '邮箱', 'required|valid_email');
    $this->form_validation->set_rules('password', '密码', 'required|min_length[6]');
    
    if (!$this->form_validation->run()) {
        // 返回JSON格式错误信息
        $errors = $this->form_validation->error_array();
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['status' => 'error', 'errors' => $errors]));
    } else {
        // 验证通过后的业务逻辑
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['status' => 'success', 'message' => '验证通过']));
    }
}

CodeIgniter 4

  • CodeIgniter 4推荐使用控制器内置的validate()方法执行验证,验证失败时通过$this->validator->getErrors()获取数组格式的错误信息。
  • 如需单个字段的错误,可调用$this->validator->getError('字段名')。

示例代码:

public function submitApi()
{
    $validationRules = [
        'email' => 'required|valid_email',
        'password' => 'required|min_length[6]'
    ];
    
    if (!$this->validate($validationRules)) {
        // 返回JSON错误响应
        return $this->response->setJSON([
            'status' => 'error',
            'errors' => $this->validator->getErrors()
        ]);
    } else {
        // 验证通过后的处理逻辑
        return $this->response->setJSON([
            'status' => 'success',
            'message' => '验证通过'
        ]);
    }
}

内容的提问来源于stack exchange,提问作者Rhugveda Desai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 06:45:28