How to validate a property dependent on another property in Symfony 2 How to validate a property dependent on another property in Symfony 2 symfony symfony

How to validate a property dependent on another property in Symfony 2


Starting from Symfony 2.4 you can also use Expression validation constraint to achieve what you need. I do believe, that this is the most simple way to do this. It's more convenient than Callback constraint for sure.

Here's example of how you can update your model class with validation constraints annotations:

use Symfony\Component\Validator\Constraints as Assert;class Conference{    /**     * @var \DateTime     *     * @Assert\Expression(     *     "this.startDate <= this.endDate",     *     message="Start date should be less or equal to end date!"     * )     */    protected $startDate;    /**     * @var \DateTime     *     * @Assert\Expression(     *     "this.endDate >= this.startDate",     *     message="End date should be greater or equal to start date!"     * )     */    protected $endDate;}

Don't forget to enable annotations in your project configuration.

You can always do even more complex validations by using expression syntax.


Yes with the callback validator: http://symfony.com/doc/current/reference/constraints/Callback.html

On symfony 2.0:

use Symfony\Component\Validator\Constraints as Assert;use Symfony\Component\Validator\ExecutionContext;/** * @Assert\Callback(methods={"isDateValid"}) */class Conference{    // Properties, getter, setter ...    public function isDateValid(ExecutionContext $context)    {        if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {                $propertyPath = $context->getPropertyPath() . '.startDate';                $context->setPropertyPath($propertyPath);                $context->addViolation('The starting date must be anterior than the ending date !', array(), null);        }    }}

On symfony master version:

    public function isDateValid(ExecutionContext $context)    {        if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {            $context->addViolationAtSubPath('startDate', 'The starting date must be anterior than the ending date !', array(), null);        }    }

Here I choose to show the error message on the startDate field.


Another way (at least as of Symfony 2.3) is to use simple @Assert\IsTrue:

class Conference{    //...    /**     * @Assert\IsTrue(message = "Startime should be lesser than EndTime")     */    public function isStartBeforeEnd()    {        return $this->getStartDate() <= $this->getEndDate;    }    //...}

As reference, documentation.