Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 360
Martin Avatar asked Nov 19 '18 12:11

Martin


1 Answers

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()
            }
        )
    }
)
like image 178
Bartosz Zasada Avatar answered Sep 28 '22 07:09

Bartosz Zasada