Validation

Validation

Validation is a very common task in web applications. Data entered in forms needs to be validated. Data also needs to be validated before it is written into a database or passed to a web service.

Symfony provides a Validator component to handle this for you. This component is based on the JSR303 Bean Validation specification.

Installation

In applications using Symfony Flex, run this command to install the validator before using it:

  1. $ composer require symfony/validator doctrine/annotations

Note

If your application doesn’t use Symfony Flex, you might need to do some manual configuration to enable validation. Check out the Validation configuration reference.

The Basics of Validation

The best way to understand validation is to see it in action. To start, suppose you’ve created a plain-old-PHP object that you need to use somewhere in your application:

  1. // src/Entity/Author.php
  2. namespace App\Entity;
  3. class Author
  4. {
  5. private $name;
  6. }

So far, this is an ordinary class that serves some purpose inside your application. The goal of validation is to tell you if the data of an object is valid. For this to work, you’ll configure a list of rules (called constraints) that the object must follow in order to be valid. These rules are usually defined using PHP code or annotations but they can also be defined as .yaml or .xml files inside the config/validator/ directory:

For example, to indicate that the $name property must not be empty, add the following:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. class Author
    6. {
    7. /**
    8. * @Assert\NotBlank
    9. */
    10. private $name;
    11. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. name:
    5. - NotBlank: ~
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\Author">
    8. <property name="name">
    9. <constraint name="NotBlank"/>
    10. </property>
    11. </class>
    12. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints\NotBlank;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. private $name;
    9. public static function loadValidatorMetadata(ClassMetadata $metadata)
    10. {
    11. $metadata->addPropertyConstraint('name', new NotBlank());
    12. }
    13. }

Adding this configuration by itself does not yet guarantee that the value will not be blank; you can still set it to a blank value if you want. To actually guarantee that the value adheres to the constraint, the object must be passed to the validator service to be checked.

Tip

Symfony’s validator uses PHP reflection, as well as “getter” methods, to get the value of any property, so they can be public, private or protected (see Constraint Targets).

Using the Validator Service

Next, to actually validate an Author object, use the validate() method on thevalidatorservice (which implementsSymfony\Component\Validator\Validator\ValidatorInterface). The job of thevalidatoris to read the constraints (i.e. rules) of a class and verify if the data on the object satisfies those constraints. If validation fails, a non-empty list of errors (Symfony\Component\Validator\ConstraintViolationList` class) is returned. Take this simple example from inside a controller:

  1. // ...
  2. use App\Entity\Author;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Component\Validator\Validator\ValidatorInterface;
  5. // ...
  6. public function author(ValidatorInterface $validator)
  7. {
  8. $author = new Author();
  9. // ... do something to the $author object
  10. $errors = $validator->validate($author);
  11. if (count($errors) > 0) {
  12. /*
  13. * Uses a __toString method on the $errors variable which is a
  14. * ConstraintViolationList object. This gives us a nice string
  15. * for debugging.
  16. */
  17. $errorsString = (string) $errors;
  18. return new Response($errorsString);
  19. }
  20. return new Response('The author is valid! Yes!');
  21. }

If the $name property is empty, you will see the following error message:

  1. Object(App\Entity\Author).name:
  2. This value should not be blank

If you insert a value into the name property, the happy success message will appear.

Tip

Most of the time, you won’t interact directly with the validator service or need to worry about printing out the errors. Most of the time, you’ll use validation indirectly when handling submitted form data. For more information, see how to validate Symfony forms.

You could also pass the collection of errors into a template:

  1. if (count($errors) > 0) {
  2. return $this->render('author/validation.html.twig', [
  3. 'errors' => $errors,
  4. ]);
  5. }

Inside the template, you can output the list of errors exactly as needed:

  1. {# templates/author/validation.html.twig #}
  2. <h3>The author has the following errors</h3>
  3. <ul>
  4. {% for error in errors %}
  5. <li>{{ error.message }}</li>
  6. {% endfor %}
  7. </ul>

Note

Each validation error (called a “constraint violation”), is represented by a Symfony\Component\Validator\ConstraintViolation object.

Constraints

The validator is designed to validate objects against constraints (i.e. rules). In order to validate an object, simply map one or more constraints to its class and then pass it to the validator service.

Behind the scenes, a constraint is simply a PHP object that makes an assertive statement. In real life, a constraint could be: 'The cake must not be burned'. In Symfony, constraints are similar: they are assertions that a condition is true. Given a value, a constraint will tell you if that value adheres to the rules of the constraint.

Supported Constraints

Symfony packages many of the most commonly-needed constraints:

Basic Constraints

These are the basic constraints: use them to assert very basic things about the value of properties or the return value of methods on your object.

String Constraints

Comparison Constraints

Number Constraints

Date Constraints

Choice Constraints

File Constraints

Financial and other Number Constraints

Other Constraints

You can also create your own custom constraints. This topic is covered in the How to Create a Custom Validation Constraint article.

Constraint Configuration

Some constraints, like NotBlank, are simple whereas others, like the Choice constraint, have several configuration options available. Suppose that the Author class has another property called genre that defines the literature genre mostly associated with the author, which can be set to either “fiction” or “non-fiction”:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. class Author
    6. {
    7. /**
    8. * @Assert\Choice(
    9. * choices = {"fiction", "non-fiction"},
    10. * message = "Choose a valid genre."
    11. * )
    12. */
    13. private $genre;
    14. // ...
    15. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. genre:
    5. - Choice: { choices: [fiction, non-fiction], message: Choose a valid genre. }
    6. # ...
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\Author">
    8. <property name="genre">
    9. <constraint name="Choice">
    10. <option name="choices">
    11. <value>fiction</value>
    12. <value>non-fiction</value>
    13. </option>
    14. <option name="message">Choose a valid genre.</option>
    15. </constraint>
    16. </property>
    17. <!-- ... -->
    18. </class>
    19. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. private $genre;
    9. // ...
    10. public static function loadValidatorMetadata(ClassMetadata $metadata)
    11. {
    12. // ...
    13. $metadata->addPropertyConstraint('genre', new Assert\Choice([
    14. 'choices' => ['fiction', 'non-fiction'],
    15. 'message' => 'Choose a valid genre.',
    16. ]));
    17. }
    18. }

The options of a constraint can always be passed in as an array. Some constraints, however, also allow you to pass the value of one, “default”, option in place of the array. In the case of the Choice constraint, the choices options can be specified in this way.

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. class Author
    6. {
    7. /**
    8. * @Assert\Choice({"fiction", "non-fiction"})
    9. */
    10. private $genre;
    11. // ...
    12. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. genre:
    5. - Choice: [fiction, non-fiction]
    6. # ...
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\Author">
    8. <property name="genre">
    9. <constraint name="Choice">
    10. <value>fiction</value>
    11. <value>non-fiction</value>
    12. </constraint>
    13. </property>
    14. <!-- ... -->
    15. </class>
    16. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. private $genre;
    9. public static function loadValidatorMetadata(ClassMetadata $metadata)
    10. {
    11. // ...
    12. $metadata->addPropertyConstraint(
    13. 'genre',
    14. new Assert\Choice(['fiction', 'non-fiction'])
    15. );
    16. }
    17. }

This is purely meant to make the configuration of the most common option of a constraint shorter and quicker.

If you’re ever unsure of how to specify an option, either check the namespace Symfony\Component\Validator\Constraints for the constraint or play it safe by always passing in an array of options (the first method shown above).

Constraints in Form Classes

Constraints can be defined while building the form via the constraints option of the form fields:

  1. public function buildForm(FormBuilderInterface $builder, array $options)
  2. {
  3. $builder
  4. ->add('myField', TextType::class, [
  5. 'required' => true,
  6. 'constraints' => [new Length(['min' => 3])],
  7. ])
  8. ;
  9. }

Constraint Targets

Constraints can be applied to a class property (e.g. name), a public getter method (e.g. `getFullName()) or an entire class. Property constraints are the most common and easy to use. Getter constraints allow you to specify more complex validation rules. Finally, class constraints are intended for scenarios where you want to validate a class as a whole.

Properties

Validating class properties is the most basic validation technique. Symfony allows you to validate private, protected or public properties. The next listing shows you how to configure the $firstName property of an Author class to have at least 3 characters.

  • Annotations

    1. // src/Entity/Author.php
    2. // ...
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\NotBlank
    8. * @Assert\Length(min=3)
    9. */
    10. private $firstName;
    11. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. firstName:
    5. - NotBlank: ~
    6. - Length:
    7. min: 3
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\Author">
    8. <property name="firstName">
    9. <constraint name="NotBlank"/>
    10. <constraint name="Length">
    11. <option name="min">3</option>
    12. </constraint>
    13. </property>
    14. </class>
    15. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. private $firstName;
    9. public static function loadValidatorMetadata(ClassMetadata $metadata)
    10. {
    11. $metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
    12. $metadata->addPropertyConstraint(
    13. 'firstName',
    14. new Assert\Length(['min' => 3])
    15. );
    16. }
    17. }

Caution

The validator will use a value null if a typed property is uninitialized. This can cause unexpected behavior if the property holds a value when initialized. In order to avoid this, make sure all properties are initialized before validating them.

Getters

Constraints can also be applied to the return value of a method. Symfony allows you to add a constraint to any public method whose name starts with “get”, “is” or “has”. In this guide, these types of methods are referred to as “getters”.

The benefit of this technique is that it allows you to validate your object dynamically. For example, suppose you want to make sure that a password field doesn’t match the first name of the user (for security reasons). You can do this by creating an isPasswordSafe() method, and then asserting that this method must returntrue`:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. class Author
    6. {
    7. /**
    8. * @Assert\IsTrue(message="The password cannot match your first name")
    9. */
    10. public function isPasswordSafe()
    11. {
    12. // ... return true or false
    13. }
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. getters:
    4. passwordSafe:
    5. - 'IsTrue': { message: 'The password cannot match your first name' }
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\Author">
    8. <getter property="passwordSafe">
    9. <constraint name="IsTrue">
    10. <option name="message">The password cannot match your first name</option>
    11. </constraint>
    12. </getter>
    13. </class>
    14. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
    11. 'message' => 'The password cannot match your first name',
    12. ]));
    13. }
    14. }

Now, create the `isPasswordSafe() method and include the logic you need:

  1. public function isPasswordSafe()
  2. {
  3. return $this->firstName !== $this->password;
  4. }

Note

The keen-eyed among you will have noticed that the prefix of the getter (“get”, “is” or “has”) is omitted in the mappings for the YAML, XML and PHP formats. This allows you to move the constraint to a property with the same name later (or vice versa) without changing your validation logic.

Classes

Some constraints apply to the entire class being validated. For example, the Callback constraint is a generic constraint that’s applied to the class itself. When that class is validated, methods specified by that constraint are simply executed so that each can provide more custom validation.

Final Thoughts

The Symfony validator is a powerful tool that can be leveraged to guarantee that the data of any object is “valid”. The power behind validation lies in “constraints”, which are rules that you can apply to properties or getter methods of your object. And while you’ll most commonly use the validation framework indirectly when using forms, remember that it can be used anywhere to validate any object.

Learn more

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