In a typical Symfony application, validation is often applied to full objects such as DTOs or entities. Still, there are many situations where validating a single value is all we need - for example, checking whether a string contains valid JSON. Symfony Validator component makes this easy by allowing us to validate raw scalar values directly, without wrapping them inside a class. This tutorial demonstrates how to validate scalar value in Symfony 8 application.
To validate a scalar value, we can inject ValidatorInterface and call its validate method as usual. The first argument is the value itself, and the second is the constraint we want to apply.
The following code provides a basic controller example that checks whether a string is valid JSON:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Constraints\Json;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class TestController
{
#[Route('/')]
public function index(ValidatorInterface $validator): Response
{
$json = '{invalid';
$errors = $validator->validate($json, new Json());
if (count($errors) > 0) {
return new Response((string) $errors);
}
return new Response('Valid');
}
}
We are not limited to a single constraint. Symfony allows us to pass an array of constraints to the validate method, which is useful when we want to enforce several rules at once.
For instance, the following example ensures that the value is not empty and that it contains valid JSON:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Constraints\Json;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class TestController
{
#[Route('/')]
public function index(ValidatorInterface $validator): Response
{
$json = '';
$errors = $validator->validate($json, [new NotBlank(), new Json()]);
if (count($errors) > 0) {
return new Response((string) $errors);
}
return new Response('Valid');
}
}
Leave a Comment
Cancel reply