我有带有定义的 symfony2 自定义验证器:
// Nip.php
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Nip extends Constraint
{
public $message = 'This value %string% is not a valid NIP number';
//...
这是验证器代码:
// NipValidator.php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class NipValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$stringValue = (string) $value;
$nip = preg_replace('/[ -]/im', '', $stringValue);
$length = strlen($nip);
if ($length != 10) {
$this->context->addViolation(
$constraint->message,
array('%string%' => $value)
);
return;
}
//...
和我的翻译文件:
// validators.pl.yml
validator.nip: %string% to nie jest poprawny nip
服务定义:
// services.yml
services:
validator.nip:
class: BundlePath\Validator\Constraints\NipValidator
tags:
- { name: validator.constraint_validator, alias: validator.nip }
我尝试将 $constraint->message 替换为 'validator.nip' 但这仅将 'validator.nip' 显示为字符串,并且无法解析为已翻译的消息。
CustomValidator 运行良好,唯一的问题是启用翻译。
我已经阅读了来自 symfony.com 的关于约束翻译的文档,但这适用于标准验证器而不是自定义验证器。
最佳答案
我认为问题在于您如何定义消息 key 并构建验证翻译域。
您的自定义 nip 约束消息作为翻译键会更好:
$message = error.nip.invalidNumber;
翻译文件应为:
error:
nip:
invalidNumber: %string% to nie jest poprawny nip
您已定义与实际服务名称 (validator.nip) 相同的服务别名。我不确定这是否会导致错误,但为了安全起见,我会将别名设置为 app_nip_validator。
最后,在您的自定义验证器中,删除返回并更改您构建违规的方式。
if ($length != 10) {
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
// return;
}
关于validation - 使用参数翻译自定义验证器消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22113296/