2015-12-12 100 views
0

我試圖在更改密碼功能上添加驗證,但它不起作用。驗證不起作用 - CakePHP 3

我已經加入

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

     // } 
    // } 
    } 

將它不驗證保存數據。解決辦法是什麼 ?

+1

請張貼的代碼方法'createEntity()'。 –

+0

你可以打印出你使用過的'$ user'的價值嗎? – Beginner

回答

1

沒有徹底檢查過你的代碼,我的第一個想法是CakePHP 3已經爲此提供了內置的驗證器compareWith

嘗試將驗證規則如下:

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

    ] 
]); 

此外,檢查兩個new_passwordrepeat_password$_accessible陣列中被設置爲true

+0

但是也不行 –

0
public $validate = array(

    'password' => array(
     'required' => array(
      'rule' => array('notEmpty'), 
      'message' => 'A password is required' 
     ), 
     'min_length' => array(
      'rule' => array('minLength', '6'), 
      'message' => 'Password must have a mimimum of 6 characters' 
     ) 
    ), 

    'password_confirm' => array(
     'required' => array(
      'rule' => array('notEmpty'), 
      'message' => 'Please confirm your password' 
     ), 
     'equaltofield' => array(
      'rule' => array('equaltofield','password'), 
      'message' => 'Both passwords must match.' 
     ) 
    ), 




) 

請寫出你的模型代碼詳細請查看以下鏈接 http://miftyisbored.com/a-complete-login-and-authentication-application-tutorial-for-cakephp-2-3/