skip to Main Content

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


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

    Login or Signup to reply.
  2. There is no AssertRequired constraint.

    Since Symfony 5.4 you can use Attributes to combine constraints:

    #[AssertAll([
        new AssertNotNull(),
        new AssertRange(min: 3),
    ])]
    

    or

    #[AssertCollection(
        fields: [
            'foo' => [
                new AssertNotNull(),
                new AssertRange(min: 3),
            ],
            'bar' => new AssertRange(min: 5),
            'baz' => new AssertRequired([new AssertEmail()]),
        ]
    )]
    

    https://symfony.com/blog/new-in-symfony-5-4-nested-validation-attributes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search