我添加了一条规则来检查更新用户记录中的先前密码,但该规则也适用于创建记录,我添加了“更新”但仍然无效。
$validator
->scalar('password')
->maxLength('password', 25)
->notEmpty('password', 'Password is required', 'create')
->allowEmpty('password', 'update')
->add('password', 'validFormat', [
'rule' => ['custom', '/^(?=.*[!@$])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,16}$/i'],
'message' => __('Minimum 6 character & alphanumeric with one symbol(!@$) is Required.'),
'allowEmpty' => true
])
->add('password', 'custom', [
'rule' => function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if (!(new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message' => 'You cannot use your previous password',
'allowEmpty' => true
], 'update');
答案 0 :(得分:0)
添加updated
没有做任何事情,因为它不是CakePHP支持的。
如果您阅读Custom Validation Rules,您会看到可以使用$ context ['newRecord']来确定这是更新还是创建。
因此,验证函数的第一行可能类似于
if ($context['newRecord']){
return true; //new passwords are always valid!
}
替代方法是检查$ user变量并添加else分支
if($user){
//you already have code here
}else{
//add this else to return TRUE because for new user, new password is OK
return true;
}