您可以编写自定义 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;
}
尽管对于这样一个简单的事情来说似乎有点多,但经验表明,人们需要一个日期范围验证器,而不仅仅是一次。