在 Symfony 2 中,我有一个我想要验证的名称字段。如果它包含一个数字,我想显示一条消息。我的代码是:
//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;
但是当我在字段中输入数字时,我看到了这条消息:
Please match the requested format
因为我的域代码如下:
<input type="text" id="mzm_testbundle_category_name" name="mzm_testbundle_category[name]" required="required" maxlength="255" pattern="((?![0-9]).)*">
输入标签有一个模式,我看到的错误来自 HTML5。我该如何解决这个问题?
最佳答案
您看到的消息并非直接来自 Symfony 验证器。表单框架尽可能定义 HTML 验证,消息确实来自客户端验证。
覆盖客户端消息
Constraint API's setCustomValidity()可用于更新客户端消息。
您可以在定义字段时执行此操作:
$builder->add(
'name',
'text',
[
'attr' => [
'oninvalid' => "setCustomValidity('Your name cannot contain a number')"
]
]
));
或在 Twig 模板中:
{{ form_row(
form.name,
{
'attr': {
'oninvalid': "setCustomValidity('Your name cannot contain a number')"
}
}
) }}
禁用客户端验证
您还可以禁用 HTML 验证:
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
引用资料
关于php - Symfony 2 验证消息被默认验证覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129356/