Symfony2: Custom Validation Constraint


To add a custom validator constraint, add this to your config.yml (as an example…):

framework:
    validation:
      enabled: true
      annotations:
          namespaces:
              test: Book\Store4Bundle\validator\

The namespaces is a list of the namespaces to your custom constraints, for example now when you do @test:Etc symfony will search for a class named Etc on the namespace assosiated with test, which is: book/store4bundle/validator. So you do this one time only and then you create your classes in the correct namespace and you´re good to go! Nelow you can see an object that uses the custom validator on one of it´s fields.

class Test
{
    /**
     * @test:AlwaysFail()
     */
    public $name;
}

AllwaysFail and Validator class:

<?php
// AlwaysFail.php
namespace Book\Store4Bundle\validator;

use Symfony\Component\Validator\Constraint;

class AlwaysFail extends Constraint
{
      public $message = 'This value is not a valid TEST';

    public function getTargets ()
    {
        return Constraint::PROPERTY_CONSTRAINT;
    }
}

?>

And the validator class:

<?php
// AlwaysFailValidator.php   <-- Symfony automatically search for this class! CLASS+Validator.php
namespace Book\Store4Bundle\validator;

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

class AlwaysFailValidator extends ConstraintValidator
{

    public function isValid ( $value, Constraint $constraint )
    {
        $this->setMessage("Nope, always fail!");
        return false;
    }
}

?>

The above example will search for a class named AlwaysFail in the Book\Store4Bundle\validator namespace.

The class must extends Constraint, and it must exists another class named %CLASSNAME%Validator which must extends ConstraintValidator. In the above example it would be AlwaysFailValidator.

It was actually hard to figure this out, because the documentation is not very clear, i had to search for “assert” on the symfony files, and i got to line 488 of the file FrameworkExtension.php (from the zip BETA1 Symfony2), then i knew that the new namespaces were declared in the config and also that the class in charge of loading annotations is called AnnotationLoader.php…

You can see more information on all the constraint that comes with Symfony investigating this namespace: Symfony\Component\Validator\Constraints;

Now you can read the official documentation understanding how actually making this work!

Advertisements