Creative Commons License
This work is licensed under a
Creative Commons
Attribution-Share Alike 3.0
Unported License.

Master Symfony2 fundamentals

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).
trainings.sensiolabs.com

Symfony hosting done right

ServerGrove, outstanding support at the right price for your Symfony hosting needs.
servergrove.com

L'audit Qualité par SensioLabs

200 points de contrôle de votre applicatif web.
audit.sensiolabs.com
2.0 version

How to create a Custom Validation Constraint

How to create a Custom Validation Constraint

You can create a custom constraint by extending the base constraint class, Constraint. Options for your constraint are represented as public properties on the constraint class. For example, the Url constraint includes the message and protocols properties:

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Protocol extends Constraint
{
    public $message = 'This value is not a valid protocol';
    public $protocols = array('http', 'https', 'ftp', 'ftps');
}

Note

The @Annotation annotation is necessary for this new constraint in order to make it available for use in classes via annotations.

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

// 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), Symfony2 will automatically look for another class, MyConstraintValidator when actually performing the validation.

The validator class is also simple, and only has one required method: isValid. Furthering our example, take a look at the ProtocolValidator as an example:

namespace Symfony\Component\Validator\Constraints;

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

class ProtocolValidator extends ConstraintValidator
{
    public function isValid($value, Constraint $constraint)
    {
        if (!in_array($value, $constraint->protocols)) {
            $this->setMessage($constraint->message, array('%protocols%' => $constraint->protocols));

            return false;
        }

        return true;
    }
}

Note

Don't forget to call setMessage to construct an error message when the value is invalid.

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 an alias attribute:

  • YAML
    services:
        validator.unique.your_validator_name:
            class: Fully\Qualified\Validator\Class\Name
            tags:
                - { name: validator.constraint_validator, alias: alias_name }
    
  • 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>
    
  • PHP
    $container
        ->register('validator.unique.your_validator_name', 'Fully\Qualified\Validator\Class\Name')
        ->addTag('validator.constraint_validator', array('alias' => 'alias_name'))
    ;
    

Your constraint class should now use this alias to reference the appropriate validator:

public function validatedBy()
{
    return 'alias_name';
}

As mentioned above, Symfony2 will automatically look for a class named after the constraint, with Validator appended. If your constraint validator is defined as a service, it's important that you override the validatedBy() method to return the alias used when defining your service, otherwise Symfony2 won't use the constraint validator service, and will instantiate the class instead, without any dependencies injected.

Class Constraint Validator

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

public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

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

class ProtocolClassValidator extends ConstraintValidator
{
    public function isValid($protocol, Constraint $constraint)
    {
        if ($protocol->getFoo() != $protocol->getBar()) {

            // bind error message on foo property
            $this->context->addViolationAtSubPath('foo', $constraint->getMessage(), array(), null);

            return false;
        }

        return true;
    }
}