我正在查看Symfony2验证参考,但找不到我需要的内容。
我有一个类Employment,其开始日期为,结束日期为我想添加一个\\Assert((,它验证StartDate总是在EndDate之前。是否有将类属性作为验证约束进行比较的标准方法,或者我应该创建一个自定义验证约束?
class Employment {
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
* @Expose()
*/
protected $id;
/**
* @ORMColumn(type="datetime")
* @Expose()
* @AssertDateTime()
*/
protected $startDate;
/**
* @ORMColumn(type="datetime", nullable=TRUE)
* @Expose()
* @AssertDateTime()
*/
protected $endDate;
...
}
您可以向实体添加一个验证getter-Symfony2 validation Getters
在您的验证中
AcmeYourBundleEntityEmployment:
getters:
datesValid:
- "True": { message: "The start date must be before the end date" }
然后在你的实体
public function isDatesValid()
{
return ($this->startDate < $this->endDate);
}
还有另一个解决方案:使用表达式语言进行验证:
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMColumn(type="date", nullable=true)
* @AssertDate()
*/
private $startDate;
/**
* @ORMColumn(type="date", nullable=true)
* @AssertDate()
* @AssertExpression(
* "this.getStartDate() < this.getEndDate()",
* message="The end date must be after the start date"
* )
*/
private $endDate;
如果需要,可以将此约束添加到$startDate
。
您可以编写一个自定义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: XXXFormExtensionsBundleValidatorConstraintsDateRangeValidator
services:
daterange.validator:
class: %register.daterange.validator.class%
tags:
- { name: validator.constraint_validator, alias: daterange_validator }
并在您的实体中使用它:
use XXXFormExtensionsBundleValidatorConstraints as FormAssert;
/**
*
* @FormAssertDateRange()
*/
class Contact extends Entity
{
private $startDate;
private $endDate;
}
尽管这对于这样一件简单的事情来说似乎有点过分,但经验表明,一个人需要一个日期范围验证器的次数不止一次。