How to Validate Raw Values (Scalar Values and Arrays)

How to Validate Raw Values (Scalar Values and Arrays)

Usually you will be validating entire objects. But sometimes, you want to validate a simple value - like to verify that a string is a valid email address. From inside a controller, it looks like this:

  1. // ...
  2. use Symfony\Component\Validator\Constraints as Assert;
  3. use Symfony\Component\Validator\Validator\ValidatorInterface;
  4. // ...
  5. public function addEmail($email, ValidatorInterface $validator)
  6. {
  7. $emailConstraint = new Assert\Email();
  8. // all constraint "options" can be set this way
  9. $emailConstraint->message = 'Invalid email address';
  10. // use the validator to validate the value
  11. $errors = $validator->validate(
  12. $email,
  13. $emailConstraint
  14. );
  15. if (0 === count($errors)) {
  16. // ... this IS a valid email address, do something
  17. } else {
  18. // this is *not* a valid email address
  19. $errorMessage = $errors[0]->getMessage();
  20. // ... do something with the error
  21. }
  22. // ...
  23. }

By calling validate() on the validator, you can pass in a raw value and the constraint object that you want to validate that value against. A full list of the available constraints - as well as the full class name for each constraint - is available in the constraints reference section.

Validation of arrays is possible using the Collection constraint:

  1. use Symfony\Component\Validator\Constraints as Assert;
  2. use Symfony\Component\Validator\Validation;
  3. $validator = Validation::createValidator();
  4. $input = [
  5. 'name' => [
  6. 'first_name' => 'Fabien',
  7. 'last_name' => 'Potencier',
  8. ],
  9. 'email' => '[email protected]',
  10. 'simple' => 'hello',
  11. 'eye_color' => 3,
  12. 'file' => null,
  13. 'password' => 'test',
  14. 'tags' => [
  15. [
  16. 'slug' => 'symfony_doc',
  17. 'label' => 'symfony doc',
  18. ],
  19. ],
  20. ];
  21. $groups = new Assert\GroupSequence(['Default', 'custom']);
  22. $constraint = new Assert\Collection([
  23. // the keys correspond to the keys in the input array
  24. 'name' => new Assert\Collection([
  25. 'first_name' => new Assert\Length(['min' => 101]),
  26. 'last_name' => new Assert\Length(['min' => 1]),
  27. ]),
  28. 'email' => new Assert\Email(),
  29. 'simple' => new Assert\Length(['min' => 102]),
  30. 'eye_color' => new Assert\Choice([3, 4]),
  31. 'file' => new Assert\File(),
  32. 'password' => new Assert\Length(['min' => 60]),
  33. 'tags' => new Assert\Optional([
  34. new Assert\Type('array'),
  35. new Assert\Count(['min' => 1]),
  36. new Assert\All([
  37. new Assert\Collection([
  38. 'slug' => [
  39. new Assert\NotBlank(),
  40. new Assert\Type(['type' => 'string']),
  41. ],
  42. 'label' => [
  43. new Assert\NotBlank(),
  44. ],
  45. ]),
  46. new CustomUniqueTagValidator(['groups' => 'custom']),
  47. ]),
  48. ]),
  49. ]);
  50. $violations = $validator->validate($input, $constraint, $groups);

The validate() method returns a Symfony\Component\Validator\ConstraintViolationList object, which acts like an array of errors. Each error in the collection is a Symfony\Component\Validator\ConstraintViolation object, which holds the error message on its getMessage() method.

Note

When using groups with the Collection constraint, be sure to use the Optional constraint when appropriate as explained in its reference documentation.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.