Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Cookbook
  4. Validation
  5. How to Create a custom Validation Constraint
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Creating the Constraint Class
  • Creating the Validator itself
  • Using the new Validator
    • Constraint Validators with Dependencies
    • Class Constraint Validator

How to Create a custom Validation Constraint

Edit this page

Warning: You are browsing the documentation for Symfony 2.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Create a custom Validation Constraint

You can create a custom constraint by extending the base constraint class, Constraint. As an example you're going to create a simple validator that checks if a string contains only alphanumeric characters.

Creating the Constraint Class

First you need to create a Constraint class and extend Constraint:

1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Validator/Constraints/ContainsAlphanumeric.php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ContainsAlphanumeric extends Constraint
{
    public $message = 'The string "%string%" contains an illegal character: it can only contain letters or numbers.';
}

Note

The @Annotation annotation is necessary for this new constraint in order to make it available for use in classes via annotations. Options for your constraint are represented as public properties on the constraint class.

Creating the Validator itself

As you can see, a constraint class is fairly minimal. The actual validation is performed by another "constraint validator" class. The constraint validator class is specified by the constraint's validatedBy() method, which includes some simple default logic:

1
2
3
4
5
// in the base Symfony\Component\Validator\Constraint class
public function validatedBy()
{
    return get_class($this).'Validator';
}

In other words, if you create a custom Constraint (e.g. MyConstraint), Symfony will automatically look for another class, MyConstraintValidator when actually performing the validation.

The validator class is also simple, and only has one required method validate():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Validator/Constraints/ContainsAlphanumericValidator.php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContainsAlphanumericValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
            $this->context->addViolation(
                $constraint->message,
                array('%string%' => $value)
            );
        }
    }
}

Note

The validate method does not return a value; instead, it adds violations to the validator's context property with an addViolation method call if there are validation failures. Therefore, a value could be considered as being valid if it causes no violations to be added to the context. The first parameter of the addViolation call is the error message to use for that violation.

Using the new Validator

Using custom validators is very easy, just as the ones provided by Symfony itself:

  • Annotations
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Entity/AcmeEntity.php
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\Constraints as AcmeAssert;

class AcmeEntity
{
    // ...

    /**
     * @Assert\NotBlank
     * @AcmeAssert\ContainsAlphanumeric
     */
    protected $name;

    // ...
}
1
2
3
4
5
6
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\AcmeEntity:
    properties:
        name:
            - NotBlank: ~
            - AppBundle\Validator\Constraints\ContainsAlphanumeric: ~
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- src/AppBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="AppBundle\Entity\AcmeEntity">
        <property name="name">
            <constraint name="NotBlank" />
            <constraint name="AppBundle\Validator\Constraints\ContainsAlphanumeric" />
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Entity/AcmeEntity.php
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use AppBundle\Validator\Constraints\ContainsAlphanumeric;

class AcmeEntity
{
    public $name;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());
        $metadata->addPropertyConstraint('name', new ContainsAlphanumeric());
    }
}

If your constraint contains options, then they should be public properties on the custom Constraint class you created earlier. These options can be configured like options on core Symfony constraints.

Constraint Validators with Dependencies

If your constraint validator has dependencies, such as a database connection, it will need to be configured as a service in the Dependency Injection Container. This service must include the validator.constraint_validator tag and may include an alias attribute:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
# app/config/services.yml
services:
    validator.unique.your_validator_name:
        class: Fully\Qualified\Validator\Class\Name
        tags:
            - { name: validator.constraint_validator, alias: alias_name }
1
2
3
4
5
<!-- app/config/services.xml -->
<service id="validator.unique.your_validator_name" class="Fully\Qualified\Validator\Class\Name">
    <argument type="service" id="doctrine.orm.default_entity_manager" />
    <tag name="validator.constraint_validator" alias="alias_name" />
</service>
1
2
3
4
// app/config/services.php
$container
    ->register('validator.unique.your_validator_name', 'Fully\Qualified\Validator\Class\Name')
    ->addTag('validator.constraint_validator', array('alias' => 'alias_name'));

As mentioned above, Symfony will automatically look for a class named after the constraint, with Validator appended. You can override this in your constraint class:

1
2
3
4
public function validatedBy()
{
    return 'Fully\Qualified\ConstraintValidator\Class\Name'; // or 'alias_name' if provided
}

Class Constraint Validator

Beside validating a class property, a constraint can have a class scope by providing a target in its Constraint class:

1
2
3
4
public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

With this, the validator validate() method gets an object as its first argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ProtocolClassValidator extends ConstraintValidator
{
    public function validate($protocol, Constraint $constraint)
    {
        if ($protocol->getFoo() != $protocol->getBar()) {
            $this->context->addViolationAt(
                'foo',
                $constraint->message,
                array(),
                null
            );
        }
    }
}

Note that a class constraint validator is applied to the class itself, and not to the property:

  • Annotations
  • YAML
  • XML
1
2
3
4
5
6
7
/**
 * @AcmeAssert\ContainsAlphanumeric
 */
class AcmeEntity
{
    // ...
}
1
2
3
4
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\AcmeEntity:
    constraints:
        - AppBundle\Validator\Constraints\ContainsAlphanumeric: ~
1
2
3
4
<!-- src/AppBundle/Resources/config/validation.xml -->
<class name="AppBundle\Entity\AcmeEntity">
    <constraint name="AppBundle\Validator\Constraints\ContainsAlphanumeric" />
</class>
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Christopher Hertel, a Symfony contributor

    Thanks Christopher Hertel (@chertel) for being a Symfony contributor

    22 commits • 1.02K lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia