I've got a custom validation method that checks a field for token values to ensure that they are all present in the content. The method works fine, it validates as OK when all the tokens exist in the content and throws a validation error when one or more tokens are missing.
I can easily apply a validation error message to state that some of the tokens are missing when I attach my custom validation rule to my table in validationDefault()
. However, what I really want to do is set a validation message that reflects which of the tokens haven't been set. How can I dynamically set the validation message in CakePHP 3? In CakePHP 2 I used to use $this->invalidate()
to apply an appropriate message, but this no longer appears to be an option.
My code looks like this (I've stripped out my actual token check as it isn't relevant to the issue here):-
public function validationDefault(Validator $validator)
{
$validator
->add('content', 'custom', [
'rule' => [$this, 'validateRequiredTokens'],
'message' => 'Some of the required tokens are not present'
]);
return $validator;
}
public function validateRequiredTokens($check, array $context)
{
$missingTokens = [];
// ... Check which tokens are missing and keep a record of these in $missingTokens ...
if (!empty($missingTokens)) {
// Want to update the validation message here to reflect the missing tokens.
$validationMessage = __('The following tokens are missing {0}', implode(',', $missingTokens));
return false;
}
return true;
}