【问题标题】:Codeigniter - form validation 2 field required with not match valueCodeigniter - 需要表单验证 2 字段,但值不匹配
【发布时间】:2014-11-07 08:53:29
【问题描述】:

我正在尝试对必须具有不同值的 2 个字段进行验证。我只知道如何设置验证匹配值的规则。

$this->form_validation->set_rules('book1','Book1','required|matches[book2]');
$this->form_validation->set_rules('book2','Book2','required|matches[book1]');

如果我输入book1=novelbook2=novel,上面的代码将返回TRUE

如何验证每个字段的值不匹配的 2 个字段?因此,如果我输入book1=novelbook2=comic,它将返回TRUE

【问题讨论】:

    标签: php codeigniter validation


    【解决方案1】:

    您应该使用callback_方法进行自定义验证,CI表单验证库不提供notMatch类型验证规则,请参见下面的示例代码。

    $this->form_validation->set_rules('book1','Book1','required');
    $this->form_validation->set_rules('book2','Book2','required|callback__notMatch[book1]');
    

    在控制器类中放置方法

    function _notMatch($book2Value, $book1FieldName){
       if($book2Value != $this->input->post($book1FieldName){
           $this->form_validation->set_message('_notMatch', 'book1 and book2 values are not matching');
           return false;
       }
       return true;
    }
    

    【讨论】:

    【解决方案2】:

    在 codeigniter 3 中,您可以使用differs[] set 规则来强制字段值不匹配。

    $this->form_validation->set_rules('book1', 'Book 1', 'required|differs[book2]');
    $this->form_validation->set_rules('book2', 'Book 2', 'required|differs[book1]');
    

    这意味着您不需要创建不必要的回调。但是,对于旧版本,您会这样做。

    查看文档了解更多信息:Codeigniter 3 Documentation

    【讨论】:

      【解决方案3】:

      你可以像这样使用differs

       $this->form_validation->set_rules('password', 'current password', 'max_length[25]|min_length[5]|required');
       $this->form_validation->set_rules('new_password', 'new password', 'max_length[25]|min_length[5]|required|differs[password]');
       $this->form_validation->set_rules('confirm_password', 'confirm password', 'required|max_length[25]|min_length[5]|matches[new_password]');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-28
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多