Symfony2验证 - 第一个值小于秒

时间:2015-04-20 18:08:25

标签: php symfony

我有实体类型:

/**
 * @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;
}

如何检查$value1小于$value2的验证?

2 个答案:

答案 0 :(得分:2)

您可以在实体中使用Expression约束

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;
}

答案 1 :(得分:1)

基本上,作为the cookbook explains extensively,您可能希望将以下内容添加到您的实体中:

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();
        }
    }
}