7

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

2

1 Answer 1

20

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()
            }
        )
    }
)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I was looking at the All assertion, but did not figure it out, that I can pass Collection into all Assertion.
Hi how do you write this in annotation form?
Hi @reddy, sorry, I only just saw your question. I updated my answer.
How to validate if there's items > 0 :) ?
Six years later, still helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.