In most Symfony projects, validation is commonly associated with objects like entities or DTOs. However, there are plenty of real-world cases where the data we want to validate is just a plain PHP array - for example, data decoded from JSON. This tutorial explains how to validate array in Symfony 8 application.
Symfony Validator component provides Collection constraint which can be used to validate arrays. It allows us to describe the expected structure of an array and define validation rules for each key, including nested arrays.
To validate an array, we can inject ValidatorInterface and call its validate method as usual. The method takes the array to be validated as its first argument and a Collection constraint as the second.
Here is a complete example that demonstrates how array validation works in a Symfony:
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Positive;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class TestController
{
#[Route('/')]
public function index(ValidatorInterface $validator): Response
{
$data = [
'username' => 'foo',
'age' => 0,
'contact' => [
'email' => 'wrong',
'phone' => '1236547896589327',
],
];
$constraint = new Collection(
[
'username' => [new NotBlank(), new Length(min: 5)],
'age' => new Positive(),
'contact' => new Collection(
[
'email' => [new NotBlank(), new Email()],
'phone' => new Length(max: 15),
],
),
],
);
$errors = $validator->validate($data, $constraint);
if (count($errors) > 0) {
return new Response((string) $errors);
}
return new Response('Valid');
}
}
The validate method returns a ConstraintViolationList, which holds a ConstraintViolation object for every validation failure, including details such as the error message and the property path. It's easy to pinpoint exactly which part of the array caused the validation to fail.
Leave a Comment
Cancel reply