即使满足规则,codeigniter 表单验证也总是 returns false

codeigniter form validation always returns false even when rules met

问题:即使我的表单字段符合规则,codeigniter 表单验证仍然 returns false(错误)。

示例:

   public function edit(){
    $this->load->library('form_validation');

    $this->form_validation->set_rules('title', 'title', 'required|xss_clean|trim|is_unique[news.Title]');
    $this->form_validation->set_rules('description', 'description', 'required|xss_clean|trim');
    $this->form_validation->set_rules('notes', 'notes', 'required|xss_clean|trim');

    if ($this->form_validation->run() == FALSE)
    {
        $data['error'] =  '';
        $data['page_title']="Edit News";
        echo "error";

    }
    else {
    ..........

如果我将字段留空,它会告诉我输入一些内容,因为它们不能留空。如果我输入一些东西然后它 returns 错误一旦我提交表单。

你必须使用回调验证功能

你也必须传递 id

$this->form_validation->set_rules('title', 'Title', 'required|xss_clean|trim|callback_check_title');

function check_title($title) {        
    if($this->input->post('id'))
        $id = $this->input->post('id');
    else
        $id = '';
    $result = $this->news_model->check_unique_title($id, $title);
    if($result == 0)
        $response = true;
    else {
        $this->form_validation->set_message('check_title', 'Title must be unique');
        $response = false;
    }
    return $response;
}

模型中

function check_unique_title($id, $title) {
    $this->db->where('title', $title);
    if($id) {
        $this->db->where_not_in('id', $id);
    }
    return $this->db->get('news')->num_rows();
}

它适用于插入和更新

不需要回调函数

问题是:未加载 codeigniter 数据库 class; 你应该加载数据库: $this->load->database();在 运行

之前
if ($this->form_validation->run() == FALSE)
{
    $data['error'] =  '';
    $data['page_title']="Edit News";
    echo "error";

}