Symfony 2 验证消息

问题描述:

在 symfony 2 中,我有一个 name 归档,我想验证它,如果它包含数字,我想显示一条消息.我的代码是:

In symfony 2 i have a name filed that i want to validate it and if it contains number I want to show a message. My code is:

//Entity/Product.php
 /**
     * @ORM\Column(name="`name`", type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\NotNull()
     * @Assert\Regex(pattern="/[0-9]/",match=false,message="Your name cannot contain a number")
     */
    protected $name;

但是当我在字段中写入数字时,我看到此消息 请匹配请求的格式 因为我的字段代码如下所示:

But when i write a number in field i see this message Please match the requested format because my field code is like below:

<input type="text" id="mzm_testbundle_category_name" name="mzm_testbundle_category[name]" required="required" maxlength="255" pattern="((?![0-9]).)*">

input 标签有一个模式,我看到的错误来自 HTML5.我该如何解决这个问题?

input tag has a pattern and error that i see is from HTML5. How can i resolsve this problem?

您看到的消息并非直接来自 Symfony 验证器.表单框架在可能的情况下定义了 html5 验证,并且消息确实来自客户端验证.

The message you see is not coming from the Symfony validator directly. Form framework defines an html5 validation when possible, and the message is indeed coming from the client side validation.

覆盖客户端消息

约束API 的 setCustomValidity() 可用于更新客户端消息.

Constraint API's setCustomValidity() can be used to update the client side message.

您可以在定义字段时执行此操作:

You can either do it while defining a field:

$builder->add(
    'name',
    'text',
    [
        'attr' => [
            'oninvalid' => "setCustomValidity('Your name cannot contain a number')"
        ]
    ]
));

或在树枝模板中:

{{ form_row(
       form.name, 
       {
           'attr': {
               'oninvalid': "setCustomValidity('Your name cannot contain a number')"
           } 
       }
 ) }}

禁用客户端验证

您也可以禁用 html5 验证:

You could also disable the html5 validation:

{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}

参考资料