Validation
Validation
Validation
constraint: set of rules
// src/Entity/Author.php
namespace App\Entity;
// ...
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
#[Assert\NotBlank]
private string $name;
}
// ...
public function author(ValidatorInterface $validator): Response
{
$author = new Author();
// ... do something to the $author object
$errors = $validator->validate($author);
if (count($errors) > 0) {
/*
* Uses a __toString method on the $errors variable which is a
* ConstraintViolationList object. This gives us a nice string
* for debugging.
*/
$errorsString = (string) $errors;
return new Response($errorsString);
}
return new Response('The author is valid! Yes!');
}Constraints: notblank, blank, isnull, istrue, meila, ip, json, equalto, date, choice..
Constraint Configuration
Constraints targets
properties
getters (get, has, is)
class: callback constraint
Custom constraints
Inside validate(), you don't need to return a value. Instead, you add violations to the validator's context property and a value will be considered valid if it causes no violations.
validation groups
sequentially apply validation groups: in order to avoid multiple error message
validation callback