Home > database >  Symfony nested constraints don't work properly
Symfony nested constraints don't work properly

Time:01-16

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 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.

$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?

CodePudding user response:

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

CodePudding user response:

There is no Assert\Required constraint.

Since Symfony 5.4 you can use Attributes to combine constraints:

#[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

  • Related