【发布时间】:2013-11-15 13:28:45
【问题描述】:
我使用 de oficial documentation 创建了多个验证器,它们都可以正常工作,但只有在我单独使用时。 在一个包中我定义了这个:
# Resources/config/validation.ynl
SF\SomeBundle\Entity\SomeEntity:
properties:
name:
- NotBlank: ~
- SF\UtilsBundle\Validator\Constraints\ContainsAlphanumeric: ~
- SF\UtilsBundle\Validator\Constraints\MinLength: ~
ContainstAlphanumeric 类验证器:
if (!preg_match('/^[a-z\d_]$/i', $value, $matches)) {
$this->context->addViolation($constraint->message, array('%string%' => $value));
}
MinLength 类验证器
$min = 5;
if( strlen($value) < $min )
{
$this->context->addViolation($constraint->message, array('%string%' => $value, '%min_length%' => $min));
}
所以,当我提交表单并且输入的值为“q”时,验证器 MinLength 返回长度错误,但如果相同的输入具有值“qwerty”,验证器包含字母数字返回非法字符消息。
有什么想法吗?
编辑:
我更改了 Resources/config/validation.yml 文件以使用本机 SF2 Contraints 长度验证器:
properties:
name:
- NotBlank: ~
- Length: { min: 5, minMessage: "El nombre debe tener almenos {{ limit }} caracteres." }
- SF\UtilsBundle\Validator\Constraints\ContainsAlphanumeric: ~
我发现了一个新行为:一些错误显示在树枝模板中
{{ form_errors(form) }}
和其他错误使用
{{ form_errors(form.some_field) }}
这很奇怪!
【问题讨论】:
-
我应该提到你应该使用内置的
Length验证器,而不是自己编写。我还推荐Regex验证器。 symfony.com/doc/current/reference/constraints/Regex.html
标签: php validation symfony symfony-2.3