doushao1087 2016-11-15 18:56
浏览 11
已采纳

CodeIgniter - 验证不会发生

I am doing a validation using Code Igniter. I have a simple form which used to create / update a product record.

public function productSave($params) {
    if (!$this->validate($params)) {
        return FALSE;
    }
    $id_col_value = $params['product_id'];

    if ($id_col_value) {
        // update
        $this->db->where("product_id", $id_col_value);
        return $result = $this->db->update("product", $params);
    } else {
        // insert
        return $result = $this->db->insert("product", $params);
    }
}

My validation function looks like this,

protected function validate($params) {
    $this->form_validation->set_rules("name", "", "trim|required");
    $this->form_validation->set_data($params);
    if ($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        if ( $errors ){
            return FALSE;
        }
    }
    return TRUE;
}

Now the problem

When inserting (when product_id is null) it validates. But when we have a product_id it does not validates.

My payload ($params) looks like this,

Array
(
    [product_id] => 1 // this is NULL when we do inserting
    [name] => Test Name
)

I can't figure out what I am doing wrong here and why the validation not work for updating. I use the same code for both cases.

Please Help! Thanks in advance!

  • 写回答

2条回答 默认 最新

  • douhui9380 2016-11-17 17:23
    关注

    I figure it out.

    "We have to call the set_data() method before defining any validation rules."

    Which is in the Documentation of CI.

    So, basically, I call $this->form_validation->set_data($params); first and then, I call $this->form_validation->set_rules("name", "", "trim|required");.

    This will solve the problem.

    Hope this helps anyone with the same error!!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序