如何在更新 CakePHP 中的记录期间创建自定义验证规则
how to create Custom Validation Rule for during Update a record in CakePHP
我在更新用户记录时添加了一个规则来检查以前的密码,但该规则也适用于创建记录,我添加了 'update' 但它仍然不起作用。
$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');
添加 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;
}
我在更新用户记录时添加了一个规则来检查以前的密码,但该规则也适用于创建记录,我添加了 'update' 但它仍然不起作用。
$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');
添加 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;
}