【问题标题】:CakePHP 3 - Compare passwordsCakePHP 3 - 比较密码
【发布时间】:2015-02-09 02:22:21
【问题描述】:

我有两个字段“密码”(该字段在数据库中)和confirm_password(该字段不在数据库中)

好吧,我需要比较密码 == confirm_password.. 但我不知道为“confirm_password”创建自定义验证...是否需要在数据库中包含此字段?

我该怎么做?

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    通常,您可以通过$context 参数访问custom validation rule 中的所有数据,这些数据存储在data 键中,即$context['data']['confirm_password'],然后您可以将其与当前字段值进行比较。

    $validator->add('password', 'passwordsEqual', [
        'rule' => function ($value, $context) {
            return
                isset($context['data']['confirm_password']) &&
                $context['data']['confirm_password'] === $value;
        }
    ]);
    

    话虽如此,最近引入了 compareWith 验证规则,它正是这样做的。

    https://github.com/cakephp/cakephp/pull/5813

    $validator->add('password', [
        'compare' => [
            'rule' => ['compareWith', 'confirm_password']
        ]
    ]);
    

    【讨论】:

    • 如何设置消息?使用“compareWith”的“密码无效”
    • 好的,只是 'message' => 'Password Invalid".. 但我想知道,我该如何在确认密码字段下方显示此消息?因为它会在密码字段下方显示..
    • @ThiagoMoraes 只需为confirm_password 字段添加相同的规则,然后与password 进行比较。
    • 我很困惑,这个方法在CakePHP 2中已经存在了。为什么在CakePHP 3正式发布后才添加它?
    • @Jordy 我不知道你指的是什么,但 compareWith 在 CakePHP 2.x 中不可用
    【解决方案2】:

    现在验证器类中有一个方法调用 sameAs,适用于 3.2 或更高版本。

     $validator -> sameAs('password_match','password','Passwords not equal.');
    

    API

    【讨论】:

      【解决方案3】:

      我知道这是迟到的答案,但会对其他人有所帮助。

      // Your password hash value (get from database )
      $hash = '$2y$10$MC84b2abTpj3TgHbpcTh2OYW5sb2j7YHg.Rj/DWiUBKYRJ5./NaRi';
      $plain_text = '123456'; // get from form and do not make hash. just use what user entred.
        
      if (password_verify($plain_text, $hash)) {
          echo 'Password is valid!';
      } else {
          echo 'Invalid password.';
      }
      

      $hasher = new DefaultPasswordHasher();
      $check = $hasher->check($plain_text,$hash); // it will return true/false
      

      【讨论】:

        猜你喜欢
        • 2014-05-12
        • 2017-07-23
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多