Search code examples
symfonysymfony4

How to validate array of arrays in Symfony 4


I want to know how can I validate array of arrays in symfony. My validation rules are:

  1. User - NotBlank
  2. Date - Date and NotBlank
  3. Present - NotBlank

So far I have done this:

$validator = Validation::createValidator();

$constraint = new Assert\Collection(array(
        'user' => new Assert\NotBlank(),
        'date' => new Assert\Date(),
        'present' => new Assert\NotBlank()
));

$violations = $validator->validate($request->request->get('absences')[0], $constraint);

But the problem is that it only allows to validate single array eg.
$request->request->get('absences')[0].

Here is how the array looks like:

enter image description here


Solution

  • You have to put the Collection constraint inside All constraint:

    When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.

    So, your code will probably look like this:

    $constraint = new Assert\All(['constraints' => [
        new Assert\Collection([
            'user' => new Assert\NotBlank(),
            'date' => new Assert\Date(),
            'present' => new Assert\NotBlank()
        ])
    ]]);
    

    Update: if you want to use annotations for this, it'll look something like this:

    @Assert\All(
        constraints={
            @Assert\Collection(
                fields={
                    "user"=@Assert\NotBlank(),
                    "date"=@Assert\Date(),
                    "present"=@Assert\NotBlank()
                }
            )
        }
    )