Symfony2验证日期时间1应在Datetime 2之前 [英] Symfony2 Validation Datetime 1 should be before Datetime 2
问题描述
我正在查看Symfony2验证参考,但我没有找到我需要的东西。
I'm looking through the Symfony2 Validation Reference but I'm not finding what I need.
我有一个就业与一个 StartDate 和结束日期。
我想添加一个\\ As @ @ Assert(),它验证了StartDate始终在EndDate 之前。
有没有比较类属性作为验证约束的标准方法,还是应该创建自定义验证约束?
I have a class Employment with a StartDate and EndDate. I would like to add an \@Assert() where it verifies that StartDate is always BEFORE EndDate. Is there a standard way of comparing class attributes as a Validation Constraint or should I create a custom validation constraint?
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;
...
}
推荐答案
您可以编写一个自定义的DateRangeValidator。
You could write a custom 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 }
并在您的实体中使用它:
And use it in your Entity:
use XXX\FormExtensionsBundle\Validator\Constraints as FormAssert;
/**
*
* @FormAssert\DateRange()
*/
class Contact extends Entity
{
private $startDate;
private $endDate;
}
尽管这似乎有点像一个简单的事情,但经验显示,那么需要一个日期范围验证器,而不仅仅是一次。
Eventhough it seems a bit much for a simple thing like that, but experience shows, that one needs a date range validator more often than just once.
这篇关于Symfony2验证日期时间1应在Datetime 2之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!