验证不起作用 - CakePHP 3

时间:2015-12-12 22:32:03

标签: cakephp cakephp-3.0 cakephp-3.x

我正在尝试在更改密码功能上添加验证,但它不起作用。

我添加了

->add('repeat_password', [
                          'equalToPassword' => [
                                                'rule' => function ($value, $context) {
                                                    return $value === $context['data']['new_password'];
                                                },
                                                'message' => __("Your password confirm must match with your password.")
                                               ]
                         ]);

Users模型 并在我的控制器

$user = $this->Users->get($this->_User['user_id']);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->createEntity($user, ['password' => $this->request->data['repeat_password']]);
           // $verify = (new DefaultPasswordHasher)->check($this->request->data['old_password'], $user->password);
           // debug($verify);
           //if ($verify) {
            if ($this->Users->save($user)) {
                $this->Flash->success('The password has been changed');
                $this->redirect(['action' => 'index']);

            } else {
                $this->Flash->error('Password could not be issued');

            }
           }
        //   else {

           //    $this->Flash->error('Password Do not match');

        //   }
     //   }
    }

它保存数据而不进行验证。解决方案是什么?

2 个答案:

答案 0 :(得分:1)

如果没有彻底检查您的代码,我首先想到的是CakePHP 3已经为此提供了内置验证器compareWith

尝试按如下方式设置验证规则:

$validator->add('repeat_password', [
    'compareWith' => [
        'rule' => ['compareWith', 'new_password'],
        'message' => __("Your password confirm must match with your password.")

    ]
]);

另外,请检查new_password数组中的repeat_passwordtrue是否都设置为$_accessible

答案 1 :(得分:0)

h.dup.update(h) { |_, v| v.size }
#=> { 1 => 4, 2 => 1, 3 => 3 }

h
#=> { 1 => [9, 2, 3, 4], 2 => [6], 3 => [5, 7, 1] }

请在您的模型中更详细地编写代码,请查看以下链接 http://miftyisbored.com/a-complete-login-and-authentication-application-tutorial-for-cakephp-2-3/