首页 文章

Codeigniter表格验证匹配规则(密码)

提问于
浏览
4

我正在尝试在我的Controller中编写表单验证规则以提交更改密码表单,我也在其中检查旧密码 . 我从db获取旧密码(当前)并将其放在隐藏的输入字段中 .

我的规则很简单,如下所示

$config=array(
            array(
                'field'   => 'old_password',
                'label'   => 'oldpass',
                'rules'   => 'trim|required'
            ),
            array(
                'field'   => 'conf_password',
                'label'   => 'connewpass',
                'rules'   => 'trim|required|matches[password]'
            ),
            array(
                'field'   => 'password',
                'label'   => 'newpass',
                'rules'   => 'trim|required'
            )

我保存当前密码的表单中隐藏的输入字段就像

<input type="hidden" name="old_pass" value="<?php echo $user['password']?>">

我知道规则中的匹配(字段名称)用于匹配两个字段值,但我遇到的问题是来自db的密码是md5加密的 . 如何加密来自表单的密码并与规则中的旧密码字段匹配?

3 回答

  • 14

    不需要在隐藏字段中放置旧密码哈希 . 它甚至不安全 . 您可以为自己的自定义验证创建回调函数 . 请注意我在以下代码中所做的评论 .

    $config=array(
                array(
                    'field'   => 'old_password',
                    'label'   => 'oldpass',
                    'rules'   => 'trim|required|callback_oldpassword_check' // Note: Notice added callback verifier.
                ),
                array(
                    'field'   => 'conf_password',
                    'label'   => 'connewpass',
                    'rules'   => 'trim|required|matches[password]'
                ),
                array(
                    'field'   => 'password',
                    'label'   => 'newpass',
                    'rules'   => 'trim|required'
                )
    

    在控制器的一侧创建一个方法如下

    public function oldpassword_check($old_password){
       $old_password_hash = md5($old_password);
       $old_password_db_hash = $this->yourmodel->fetchPasswordHashFromDB();
    
       if($old_password_hash != $old_password_db_hash)
       {
          $this->form_validation->set_message('oldpassword_check', 'Old password not match');
          return FALSE;
       } 
       return TRUE;
    }
    

    有关回调验证的详细信息,请访问here

    我还没有验证上面的代码 . 但希望你能找到解决问题的方法 .

  • 0

    另一种方法:

    if (!$this - > checkValidLogin($username, $old_password)) {
      $this - > form_validation - > set_rules('password', 'Password', [
        [
          'old_password',
          function($value) {
            return false;
          }
        ]
      ]);
      $this - > form_validation - > set_message('old_password', 'Old password doesn\'t match.');
    }
    
  • 1

    请使用这样的,如果您使用表单验证库,它对我有用 .

    $this->form_validation->set_rules('password', 'Password', 'required');
    $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
    

    谢谢

    编辑:代码格式

相关问题