【发布时间】:2017-04-12 01:33:06
【问题描述】:
我有一个自定义验证方法,可以检查字段中的标记值,以确保它们都存在于内容中。该方法工作正常,当所有标记都存在于内容中时它验证为 OK,并在缺少一个或多个标记时引发验证错误。
当我将自定义验证规则附加到validationDefault() 中的表时,我可以轻松地应用验证错误消息来声明缺少某些令牌。但是,我真正想做的是设置一个验证消息,以反映哪些令牌尚未设置。如何在 CakePHP 3 中动态设置验证消息?在 CakePHP 2 中,我曾经使用 $this->invalidate() 来应用适当的消息,但这似乎不再是一个选项。
我的代码看起来像这样(我已经去掉了我的实际令牌检查,因为它与这里的问题无关):-
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;
}
【问题讨论】:
标签: php validation cakephp cakephp-3.3