【发布时间】:2014-04-02 12:36:57
【问题描述】:
我有带有定义的 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 阅读了有关约束翻译的文档,但这是针对标准验证器而不是自定义验证器的。
【问题讨论】:
标签: validation symfony translation