我正在尝试在Cake
PHP 3中编写一个验证规则,检查是否设置了prename和lastname或公司名称.
验证:
$validator
->add('prename', 'custom', [
'rule' => [$this, 'validateName'],
'message' => __('Prename and lastname OR company name must be set.')
]);
$validator
->add('lastname', 'custom', [
'rule' => [$this, 'validateName'],
'message' => __('Prename and lastname OR company name must be set.')
]);
$validator
->add('name', 'custom', [
'rule' => [$this, 'validateName'],
'message' => __('Prename and lastname OR company name must be set.')
]);
规则定义:
public function validateName($check, array $context)
{
if((!empty($context['data']['prename']) && !empty($context['data']['lastname'])) || !empty($context['data']['name'])){
return true;
} else {
return false;
}
}
但验证不符合预期.如果我输入公司名称,我会得到prename和lastname的验证错误,说明这些字段是必需的.当我输入名字和姓氏时,它说公司名称是必需的.
我究竟做错了什么?
最佳答案 我也遇到了cakePhp 3.x这种奇怪的行为.我设法解决了这个问题.
以下是解决问题的代码
$validator
->notEmpty('company_name', 'Prename and lastname OR company name must be set.', function ($context){
if((!empty($context['data']['prename']) && !empty($context['data']['lastname'])) || !empty($context['data']['name'])){
return false;
} else {
return true;
}
});
$validator
->notEmpty('prename', 'Prename and lastname OR company name must be set.', function ($context){
if((!empty($context['data']['prename']) && !empty($context['data']['lastname'])) || !empty($context['data']['name'])){
return false;
} else {
return true;
}
});
$validator
->notEmpty('lastname', 'Prename and lastname OR company name must be set.', function ($context){
if((!empty($context['data']['prename']) && !empty($context['data']['lastname'])) || !empty($context['data']['name'])){
return false;
} else {
return true;
}
});
我希望这将是您的问题的解决方案.