首页 > 解决方案 > Codeigniter 匹配返回 false

问题描述

我试图将帐户保存到数据库。当使用 form_validation 验证表单时,它总是返回 false,即使我尝试插入正确的值。这是代码

public function save(){
            $params = $this->input->post();

            if(!empty($params['id_account']) && !empty($params['password']) ){

                    $this->form_validation->set_rules('confPass', 'Confirmation Password', 'matches[password]');

            }else{
                $this->form_validation->set_rules('password', 'Password', 'required');
                $this->form_validation->set_rules('confPass', 'Confirmation Password', 'required|matches[password]');
            }


            $this->form_validation->set_data($params);
            $this->form_validation->set_rules('username', 'Username', 'required');
            $this->form_validation->set_rules('id_role', 'Role', 'required');

            if ($this->form_validation->run() == TRUE) {
                unset($params['confPass']);
                $params['account_status'] = array_key_exists('account_status', $params) ? $params['account_status'] : ACCOUNT_STATUS_PENDING;  
                $this->load->model('user_model');
                $this->user_model->save($params);
                $this->session->set_flashdata('notif', '<div class="alert alert-success">Berhasil menyimpan data.</div>');
                redirect('rbac/form/account');
            } else {
                $error = validation_errors();

                echo '<pre>';
                print_r($error);
                echo '</pre>';

                var_dump($params['password']);
                var_dump($params['confPass']);
                die();
                
                // $this->session->set_flashdata('notif', '<div class="alert alert-danger">'.$error.'</div>');
                // redirect('rbac/form/account');
            }
        }

我试图返回validation_errors()$params['confPass']& $params['password'],结果如下:

确认密码字段与密码字段不匹配。

字符串(1)“e” 字符串(1)“e”

如您所见$params['confPass'],并且$params['password']匹配。

标签: phpcodeigniter

解决方案


if(!empty($params['id_account']) && !empty($params['password']) ){
                $this->form_validation->set_rules('confPass', 'Confirmation Password', 'matches[password]');
        }else{
            $this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('confPass', 'Confirmation Password', 'required|matches[password]');
        }

当您在上面写的条件为真时,即控制在 if (below) 块中

if(!empty($params['id_account']) && !empty($params['password']) )

您没有为“密码”字段设置条件,您只有确认密码规则。哪个不匹配任何东西,尽管密码匹配它总是返回 false。

您需要为密码添加验证规则

 $this->form_validation->set_rules('password', 'Password', 'required');

在确认要匹配密码的密码规则之前。

如果您的条件表明它不需要密码,您可以执行以下操作,

 $this->form_validation->set_rules('password', 'Password', 'min_length[5]');

满足您的条件但不是“必需”的任何东西,即 trim 或 min_length

希望能帮助到你。


推荐阅读