如何验证依赖于 Symfony 2 中的另一个属性的属性 [英] How to validate a property dependent on another property in Symfony 2
问题描述
是否可以验证依赖于同一类的另一个属性的模型类的属性?
Is it possible to validate a property of a model class dependent on another property of the same class?
例如,我有这个类:
class Conference
{
/** $startDate datetime */
protected $startDate;
/** $endDate datetime */
protected $endDate;
}
我希望 Symfony 2.0 验证,$startDate
必须在 $endDate
之后.
and I want that Symfony 2.0 validates, that $startDate
has to be after $endDate
.
这可以通过注释实现还是我必须手动完成?
Is this possible by annotations or do I have to do this manually?
推荐答案
是的,带有回调验证器:http://symfony.com/doc/current/reference/constraints/Callback.html
Yes with the callback validator: http://symfony.com/doc/current/reference/constraints/Callback.html
在 symfony 2.0 上:
On 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 主版本上:
On symfony master version:
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);
}
}
这里我选择在 startDate 字段上显示错误消息.
Here I choose to show the error message on the startDate field.
这篇关于如何验证依赖于 Symfony 2 中的另一个属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!