[英]Symfony nested constraints don't work properly
I came across a strange problem with Symfony validation.我在 Symfony 验证中遇到了一个奇怪的问题。 Seems that "nested" constraints don't work properly.
似乎“嵌套”约束无法正常工作。
For example, I create a string variable $data which needs to be validated.例如,我创建了一个需要验证的字符串变量 $data。
$data = 'string';
$constraint = new Assert\Type('integer');
$violations = $validator->validate($data, $constraint);
self::assertTrue($violations->count() > 0);
In this case it works properly.在这种情况下它工作正常。 We pass the string variable to the constraint which allows only integer. But if I create "nested" constraint the test won't pass.
我们将字符串变量传递给只允许 integer 的约束。但是如果我创建“嵌套”约束,测试将不会通过。
$data = 'string';
$constraint = new Assert\Required([
new Assert\Type('integer'),
]);
$violations = $validator->validate($data, $constraint);
self::assertTrue($violations->count() > 0);
In this case the test is failed.在这种情况下,测试失败。 The validator doesn't find any violations.
验证器没有发现任何违规行为。
Is it a bug?这是一个错误吗? Or do I do something wrong?
还是我做错了什么?
if you want your data to be not empty (required) and to be a number:如果您希望您的数据不为空(必需)并且是一个数字:
$data = 'string';
$validator = Validation::createValidator();
$violations = $validator->validate($data, [
new NotBlank(),
new Type(['integer'),
]);
see https://symfony.com/doc/current/components/validator.html见https://symfony.com/doc/current/components/validator.html
There is no Assert\Required
constraint.没有
Assert\Required
约束。
Since Symfony 5.4 you can use Attributes to combine constraints:从Symfony 5.4开始可以使用Attributes来组合约束:
#[Assert\All([
new Assert\NotNull(),
new Assert\Range(min: 3),
])]
or或者
#[Assert\Collection(
fields: [
'foo' => [
new Assert\NotNull(),
new Assert\Range(min: 3),
],
'bar' => new Assert\Range(min: 5),
'baz' => new Assert\Required([new Assert\Email()]),
]
)]
https://symfony.com/blog/new-in-symfony-5-4-nested-validation-attributes https://symfony.com/blog/new-in-symfony-5-4-nested-validation-attributes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.