Cakephp验证更新实体上的数据
更新实体数据时,我无法使验证正常工作。更改初始数据后,验证不起作用。下面的代码提供了一个示例:Cakephp验证更新实体上的数据,php,cakephp,model-view-controller,orm,Php,Cakephp,Model View Controller,Orm,更新实体数据时,我无法使验证正常工作。更改初始数据后,验证不起作用。下面的代码提供了一个示例: // in controller $user = $this->Users->newEntity([ 'mail' => 'wrong', 'password' => 'password', 'auth_level' => 0, ]); debug($user->getErrors())
// in controller
$user = $this->Users->newEntity([
'mail' => 'wrong',
'password' => 'password',
'auth_level' => 0,
]);
debug($user->getErrors()); // Will show error: wrong email format
$user->mail = "correct@correct.correct";
debug($user->getErrors()); // Will show no errors
$user->mail = "wrong";
debug($user->getErrors()); //Will show no errors
if (TableRegistry::get('users')->save($user)) {
// This actually executes
}
我在模型中的验证规则如下:
public function validationDefault(Validator $validator): Validator
{
$validator
->email('mail')
->add('mail', 'unique',
[
'on' => ['create', 'update'],
'rule' => 'validateUnique',
'provider' => 'table',
'message' => "Email already in use"
]
);
return $validator
}
我尝试用“on”=>“update”创建规则,但没有帮助
我试图实现的是获取一个实体,更改电子邮件地址并将其保存回数据库。保存后,电子邮件字段的格式和唯一性都不会得到验证。解决方案是始终使用
$model->patchEntity($entity, $newdata)