是與回調驗證:http://symfony.com/doc/current/reference/constraints/Callback.html
在symfony的2.0:
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
/**
* @Assert\Callback(methods={"isDateValid"})
*/
class Conference
{
// Properties, getter, setter ...
public function isDateValid(ExecutionContext $context)
{
if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {
$propertyPath = $context->getPropertyPath() . '.startDate';
$context->setPropertyPath($propertyPath);
$context->addViolation('The starting date must be anterior than the ending date !', array(), null);
}
}
}
在symfony的主版本:
public function isDateValid(ExecutionContext $context)
{
if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {
$context->addViolationAtSubPath('startDate', 'The starting date must be anterior than the ending date !', array(), null);
}
}
在這裏,我選擇顯示在起始日期字段中的錯誤信息。
標記@Psykehoe的答案應該是一個評論,而不是一個答案,因此在這裏重新評述他的評論。 'addViolationAtSubPath'從版本2.2開始已被棄用,請改用[addViolationAt](http://api.symfony.com/2.3/Symfony/Component/Validator/ExecutionContextInterface.html#method_addViolationAt)。 – astorije