使用参数翻译自定义验证器消息

时间:2014-03-01 10:45:06

标签: validation symfony translation

我有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 }

我尝试用'validator.nip'替换$ constraint->消息但是这只显示'validator.nip'作为字符串,并且它没有解析为已翻译的消息。

CustomValidator运行良好,唯一的问题是启用翻译。 我已经阅读了symfony.com关于约束翻译的文档,但这是针对标准验证器而不是自定义验证器。

3 个答案:

答案 0 :(得分:4)

我认为问题在于您如何定义消息密钥并构建验证转换域。

您的自定义压缩限制消息会更好地作为翻译密钥:

$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;
        }

答案 1 :(得分:0)

您可以在自定义验证程序中注入翻译器。

// services.yml 
   services:
        validator.nip:
            class: BundlePath\Validator\Constraints\NipValidator
            arguments: [ "@translator" ]
            tags:
                - { name: validator.constraint_validator, alias: validator.nip }

然后用它来准备信息:

// NipValidator.php
    protected $translator;

    public function __construct($translator)
    {
        $this->translator = $translator;
    }

    // ....
        $this->context->addViolation(
                $this->translator->trans($constraint->message, array(
                    '%string%' => $value,
                ))
        );

答案 2 :(得分:0)

$this->context->addViolationAt('your_path', 'translation.messate', $parameters);
相关问题