I came across a strange problem with Symfony validation.
Seems that "nested" constraints don’t work properly.
For example, I create a string variable $data which needs to be validated.
$data = 'string';
$constraint = new AssertType('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.
$data = 'string';
$constraint = new AssertRequired([
new AssertType('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?
2
Answers
if you want your data to be not empty (required) and to be a number:
see https://symfony.com/doc/current/components/validator.html
There is no
AssertRequired
constraint.Since Symfony 5.4 you can use Attributes to combine constraints:
or
https://symfony.com/blog/new-in-symfony-5-4-nested-validation-attributes