Symfony2验证日期时间1应该在日期时间2之前

时间:2013-04-12 13:16:25

标签: php symfony validation doctrine-orm assert

我正在查看Symfony2验证参考,但我找不到我需要的内容。

我有一个带有 StartDate EndDate 的类就业。 我想添加一个\ @Assert(),它验证 StartDate始终是BEFORE EndDate 。 是否存在将类属性作为验证约束进行比较的标准方法,还是应该创建自定义验证约束?

class Employment {

    /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    * @Expose() 
    */
    protected $id;

    /**
    * @ORM\Column(type="datetime") 
    * @Expose()
    * @Assert\DateTime()
    */
    protected $startDate;

    /**
    * @ORM\Column(type="datetime", nullable=TRUE)
    * @Expose()
    * @Assert\DateTime()
    */
    protected $endDate;

...
}

3 个答案:

答案 0 :(得分:30)

您可以向实体添加验证getter - Symfony2 Validation Getters

在验证中

Acme\YourBundle\Entity\Employment:
    getters:
        datesValid:
            - "True": { message: "The start date must be before the end date" }

然后在你的实体中

public function isDatesValid()
{
    return ($this->startDate < $this->endDate);
}

答案 1 :(得分:17)

您可以编写自定义DateRangeValidator。

class DateRange extends Constraint {

    public $message = "daterange.violation.crossing";
    public $emptyStartDate = "daterange.violation.startDate";
    public $emptyEndDate = "daterange.violation.endDate";

    public $hasEndDate = true;

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

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

class DateRangeValidator extends ConstraintValidator
{

    public function isValid($entity, Constraint $constraint)
    {

        $hasEndDate = true;
        if ($constraint->hasEndDate !== null) {
            $hasEndDate = $constraint->hasEndDate;
        }

        if ($entity->getStartDate() !== null) {
            if ($hasEndDate) {
                if ($entity->getEndDate() !== null) {
                    if ($entity->getStartDate() > $entity->getEndDate()) {
                        $this->setMessage($constraint->message);
                        return false;
                    }
                    return true;
                } else {
                    $this->setMessage($constraint->emptyEndDate);
                    return false;
                }
            } else {
                if ($entity->getEndDate() !== null) {
                    if ($entity->getStartDate() > $entity->getEndDate()) {
                        $this->setMessage($constraint->message);
                        return false;
                    }
                }
                return true;
            }
        } else {
            $this->setMessage($constraint->emptyStartDate);
            return false;
        }
    }

将其注册为服务:

parameters:
    register.daterange.validator.class:     XXX\FormExtensionsBundle\Validator\Constraints\DateRangeValidator

services:
    daterange.validator:
        class: %register.daterange.validator.class%
        tags:
            - { name: validator.constraint_validator, alias: daterange_validator }

并在您的实体中使用它:

use XXX\FormExtensionsBundle\Validator\Constraints as FormAssert;

/**
 *
 * @FormAssert\DateRange()
 */
class Contact extends Entity
{
    private $startDate;

    private $endDate;
}

虽然对于像这样的简单事情似乎有点多,但经验表明,人们需要更多的日期范围验证器而不仅仅是一次。

答案 2 :(得分:16)

还有另一种解决方案:Validation by using Expression Language

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Column(type="date", nullable=true)
 * @Assert\Date()
 */
private $startDate;

/**
 * @ORM\Column(type="date", nullable=true)
 * @Assert\Date()
 * @Assert\Expression(
 *     "this.getStartDate() < this.getEndDate()",
 *     message="The end date must be after the start date"
 * )
 */
private $endDate;

如果需要,可以将此约束添加到$startDate