【问题标题】:CodeIgniter - validation not happensCodeIgniter - 验证不会发生
【发布时间】:2016-11-15 18:56:24
【问题描述】:

我正在使用 Code Igniter 进行验证。我有一个用于创建/更新产品记录的简单表格。

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);
    }
}

我的验证函数是这样的,

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;
}

现在的问题

在插入时(当product_id 为空时)它会验证。但是当我们有 product_id 时,它不会验证。

我的有效载荷 ($params) 看起来像这样,

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

我无法弄清楚我在这里做错了什么以及为什么验证不适用于更新。我对这两种情况都使用相同的代码。

请帮忙!提前致谢!

【问题讨论】:

    标签: php codeigniter validation


    【解决方案1】:

    我想通了。

    "我们必须在定义任何验证之前调用 set_data() 方法 规则。”

    在 CI 的 Documentation 中。

    所以,基本上,我先打电话给$this->form_validation->set_data($params); 然后,我打电话给$this->form_validation->set_rules("name", "", "trim|required");

    这样就可以解决问题了。

    希望对遇到同样错误的人有所帮助!!!

    【讨论】:

      【解决方案2】:
      1. 检查您的 params 数组。我已经使用$params = array("product_id" => 34, "name" => "Test Name") 对其进行了检查,并且运行良好。

      2. 如果您没有插入具有该 product_id 的数据,它将无法工作。假设您已通过 product_id=3 并且此 id 在表中不可用。那么它应该如何工作呢?

      【讨论】:

      • 感谢您的回答。它仍然对我不起作用。这种行为可以在 REQUEST 类型上有所不同吗?我使用 POST 插入和 PUT 更新。
      • 分享您的 html/视图
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2011-01-20
      • 1970-01-01
      • 2014-09-03
      相关资源
      最近更新 更多