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

如何在CodeIgniter中实现表单验证?现有控制器代码哪里加验证逻辑

CodeIgniter 表单验证逻辑添加说明

你需要将表单验证逻辑放在POST请求判断块的最开头位置,也就是if ($this->input->post('nambahAlternatif')) { 这行代码的下一行,在遍历POST参数、调用模型写入数据的逻辑之前执行,确保只有验证通过的请求才会执行后续业务操作。

修改后的代码示例如下:

public function tambahAlternatif()
{
    $data['title'] = 'Tambah Alternatif';
    $data['user'] = $this->db->get_where('users', ['email' => $this->session->userdata('email')])->row_array();
    
    if ($this->input->post('nambahAlternatif')) {
        // 此处添加表单验证逻辑
        // 普通固定字段验证规则设置
        $this->form_validation->set_rules('固定字段名1', '字段显示名1', 'required|trim');
        $this->form_validation->set_rules('固定字段名2', '字段显示名2', 'required|numeric');

        // 动态生成的id_aspek_teknik前缀字段可批量设置验证规则
        foreach ($this->input->post() as $key => $value) {
            if (strpos($key, "id_aspek_teknik-") !== false) {
                $this->form_validation->set_rules($key, '技术参数项', 'required|numeric');
            }
        }

        // 验证判断逻辑
        if ($this->form_validation->run() == FALSE) {
            // 验证不通过,直接返回表单页渲染错误
            $this->load->view('你的表单视图路径', $data);
            return;
        }

        // 验证通过后再执行原有业务逻辑
        foreach ($this->input->post() as $key => $value) {
            if (strpos($key, "id_aspek_teknik-") !== false) {
                $k = str_replace('id_aspek_teknik-', '', $key);
                $this->Alternatif_model->tambahNilai($k);
            }
        }

        $this->Alternatif_model->tambahAlternatif();
        $this->session->set_flashdata('flash', 'ditambahkan');
        redirect('alternatif');

    } else {
        // 原有GET请求加载表单的逻辑
        $this->load->view('你的表单视图路径', $data);
    }
}

验证不通过时,你可以在表单视图中通过form_error('对应字段名')方法输出单个字段的错误提示,也可以用validation_errors()输出所有验证错误信息。

内容的提问来源于stack exchange,提问作者Akmal Fikri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:02