代码点火器表单验证 匹配规则(密码)


Codeigniter Form Validation Rule for match (password)

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

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

         $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 加密的。如何加密来自表单的密码并与规则中的旧通行证字段匹配?

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

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

有关回拨验证的更多详细信息,请访问此处

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

另一种方法:

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

请像这样使用,如果您使用的是表单验证库,它正在为我工作。

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

谢谢

编辑:代码格式