minLength数据验证不适用于CakePHP的Auth组件

use*_*284 3 authentication validation cakephp

假设我有一个用户注册,我正在使用Auth组件(当然允许/ user/register).

问题是如果我需要在模型中设置minLength验证规则,它不起作用,因为Auth组件哈希密码因此它总是超过我的minlength密码,即使它是空白也会通过.

我该如何解决这个问题?提前致谢!

Mik*_*ike 6

实际上,您必须重命名密码字段(例如,"pw")以防止Auth组件自动散列它.然后,如果密码通过验证规则,则对其进行散列并将password密钥保存在密钥下.这通常在beforeFilter()回调中完成,如本文所述.

还可以验证数据并在控制器中散列密码.通常不鼓励这种做法,但如果刚刚开始使用CakePHP,可能会更容易理解.

// this code would go after: if (!empty($this->data)  
//               and before: $this->User->save($this->data)

// validate the data
$this->User->set($this->data);
if ($this->User->validates()) {

    // hash the password
    $password_hash = $this->Auth->password($this->data['User']['pw'];
    $this->data['User']['password'] = $password_hash;
}
Run Code Online (Sandbox Code Playgroud)