The Validator Component
The Validator component provides tools to validate values following theJSR-303 Bean Validation specification.
Installation
- $ 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:
- use Symfony\Component\Validator\Constraints\Length;
- use Symfony\Component\Validator\Constraints\NotBlank;
- use Symfony\Component\Validator\Validation;
- $validator = Validation::createValidator();
- $violations = $validator->validate('Bernhard', [
- new Length(['min' => 10]),
- new NotBlank(),
- ]);
- if (0 !== count($violations)) {
- // there are errors, now you can show them
- foreach ($violations as $violation) {
- echo $violation->getMessage().'<br>';
- }
- }
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:
- use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
- $violations = $validator->validate(...);
- if (0 !== count($violations->findByCodes(UniqueEntity::NOT_UNIQUE_ERROR))) {
- // handle this specific error (display some message, send an email, etc.)
- }
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:
- use Symfony\Component\Validator\Validation;
- $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
- Metadata
- Loading Resources
- Validation
- How to Create a custom Validation Constraint
- How to Apply only a Subset of all Your Validation Constraints (Validation Groups)
- How to Validate Raw Values (Scalar Values and Arrays)
- How to Sequentially Apply Validation Groups
- How to Handle Different Error Levels
- How to Translate Validation Constraint Messages