The Validator Component

The Validator component provides tools to validate values following theJSR-303 Bean Validation specification.

Installation

  1. $ composer require symfony/validator

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Usage

This article explains how to use the Validator features as an independentcomponent in any PHP application. Read the Validation article tolearn about how to validate data and entities in Symfony applications.

The Validator component behavior is based on two concepts:

  • Constraints, which define the rules to be validated;
  • Validators, which are the classes that contain the actual validation logic.The following example shows how to validate that a string is at least 10characters long:
  1. use Symfony\Component\Validator\Constraints\Length;
  2. use Symfony\Component\Validator\Constraints\NotBlank;
  3. use Symfony\Component\Validator\Validation;
  4.  
  5. $validator = Validation::createValidator();
  6. $violations = $validator->validate('Bernhard', [
  7. new Length(['min' => 10]),
  8. new NotBlank(),
  9. ]);
  10.  
  11. if (0 !== count($violations)) {
  12. // there are errors, now you can show them
  13. foreach ($violations as $violation) {
  14. echo $violation->getMessage().'<br>';
  15. }
  16. }

The validate() method returns the list of violations as an object thatimplements ConstraintViolationListInterface.If you have lots of validation errors, you can filter them by error code:

  1. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
  2.  
  3. $violations = $validator->validate(...);
  4. if (0 !== count($violations->findByCodes(UniqueEntity::NOT_UNIQUE_ERROR))) {
  5. // handle this specific error (display some message, send an email, etc.)
  6. }

Retrieving a Validator Instance

The Validator class is the main accesspoint of the Validator component. To create a new instance of this class, it'srecommended to use the Validation class:

  1. use Symfony\Component\Validator\Validation;
  2.  
  3. $validator = Validation::createValidator();

This $validator object can validate simple variables such as strings, numbersand arrays, but it can't validate objects. To do so, configure theValidator class as explained in the next sections.

Learn More