0

I've got entity type of:

/**
 * @ORM\Table(name="entity")
 */
class Entity
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer", nullable=true)
     */
    private $value1;

    /**
     * @var integer
     *
     * @ORM\Column(type="integer", nullable=true)
     */
    private $value2;
}

How to check with validation that $value1 is less than $value2?

1
  • This should be useful: a validation callback that allows you to compare both values and set violations accordingly Commented Apr 20, 2015 at 18:27

2 Answers 2

2

You can use Expression constraint in your entity

use Symfony\Component\Validator\Constraints as Assert;
/**
 * @ORM\Table(name="entity")
 */
class Entity
{
    /**
     * @var integer
     * @Assert\Expression(
     *     "this.getValue2() < this.getValue1()",
     *     message="Value 1 should be less than value 2"
     *  )
     * @ORM\Column(type="integer", nullable=true)
     */
    private $value2;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Basically, as the cookbook explains extensively, you'll probably want to add the following to your entity:

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class Entity
{
    //the values stay the same
     /**
      * @Assert\Callback
      */
    public function validate(ExecutionContextInterface $context)
    {
        if ($this->value1 >= $this->value2)
        {
            $context->buildViolation('Value1 should be less than value2')
                ->atPath('value1')
                ->addViolation();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.