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

标签 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 }

我尝试将 $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/

相关文章:

php - Doctrine 如何处理多个请求?

c - 如何使用翻译器 f2c 编译单个 Fortran 对象?

symfony - 如何使用 kpnlabs 的 DoctrineBehaviors 在奏鸣曲管理中打印可翻译数据

javascript - Node.js - Express.js JWT 总是在浏览器响应中返回一个无效的 token 错误

有效 32 位有符号整数的正则表达式

javascript - 表单验证 - 禁用按钮

java - ConstraintViolationException 不能同时适用于 DTO 和 MODEL 类

php - Symfony 2 中的 jQuery 验证

php - error.message 和 error.messageKey 之间的 symfony2 区别

excel - 使用 DeepL API 翻译文本