I am trying to write a validation rule in CakePHP 3 that checks to see if a first name, last name or company name is given.
validators:
$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.')
]);
Rule Definition:
public function validateName($check, array $context)
{
if((!empty($context['data']['prename']) && !empty($context['data']['lastname'])) || !empty($context['data']['name'])){
return true;
} else {
return false;
}
}
But the check does not behave as expected. If I enter the company name, I will receive validation errors for the first and last name, indicating that the fields are required. The same thing, when I enter the name and surname, he says that the name of the company is required.
What am I doing wrong?
source
share