The Validator Component
The Validator Component¶
The Validator component provides tools to validate values following the JSR-303 Bean Validation specification.
Installation¶
You can install the component in two different ways:
- Install it via Composer (
symfony/validatoron Packagist); - Use the official Git repository (https://github.com/symfony/Validator).
Then, require the vendor/autoload.php file to enable the autoloading mechanism
provided by Composer. Otherwise, your application won't be able to find the classes
of this Symfony component.
Usage¶
The Validator component behavior is based on two concepts:
- Contraints, 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 10 characters long:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
$validator = Validation::createValidator();
$violations = $validator->validate('Bernhard', array(
new Length(array('min' => 10)),
new NotBlank(),
));
if (0 !== count($violations)) {
// there are errors, now you can show them
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
}
|
Retrieving a Validator Instance¶
The Validator class is the main access
point of the Validator component. To create a new instance of this class, it's
recommended to use the Validation class:
use Symfony\Component\Validator\Validation;
$validator = Validation::createValidator();
This $validator object can validate simple variables such as strings, numbers
and arrays, but it can't validate objects. To do so, configure the
Validator class as explained in the next sections.
Learn More¶
- Metadata
- Loading Resources
- Validation
- How to Create a custom Validation Constraint
- How to Dynamically Configure Validation Groups
- How to Apply only a Subset of all Your Validation Constraints
- 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
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.

