问题描述
我的验证在 yaml 文件中定义,如下所示;
My validations are defined in a yaml file like so;
# src/My/Bundle/Resources/config/validation.yml
My\Bundle\Model\Foo:
properties:
id:
- NotBlank:
groups: [add]
min_time:
- Range:
min: 0
max: 99
minMessage: "Min time must be greater than {{ limit }}"
maxMessage: "Min time must be less than {{ limit }}"
groups: [add]
max_time:
- GreaterThan:
value: min_time
groups: [add]
如何使用验证器约束 GreaterThan
来检查另一个属性?
例如确保 max_time 大于 min_time?
How do I use the validator constraint GreaterThan
to check against another property?
E.g make sure max_time is greater than min_time?
我知道我可以创建自定义约束验证器,但您肯定可以使用 GreaterThan
约束来实现.
希望我在这里遗漏了一些非常简单的东西
I know I can create a custom constraint validator, but surely you can do it using the GreaterThan
constraint.
Hopefully I am missing something really simple here
推荐答案
我建议你看看 自定义验证器,尤其是 Class约束验证器.
I suggest you to look at Custom validator, especially Class Constraint Validator.
我不会复制粘贴整个代码,只会复制粘贴您需要更改的部分.
I won't copy paste the whole code, just the parts which you will have to change.
定义验证器,min_time
和 max_time
是您要检查的 2 个字段.
Define the validator, min_time
and max_time
are the 2 fields you want to check.
<?php
namespace My\Bundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class CheckTime extends Constraint
{
public $message = 'Max time must be greater than min time';
public function validatedBy()
{
return 'CheckTimeValidator';
}
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
src/My/Bundle/Validator/Constraints/CheckTimeValidator.php
定义验证器:
<?php
namespace My\Bundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CheckTimeValidator extends ConstraintValidator
{
public function validate($foo, Constraint $constraint)
{
if ($foo->getMinTime() > $foo->getMaxTime()) {
$this->context->addViolationAt('max_time', $constraint->message, array(), null);
}
}
}
src/My/Bundle/Resources/config/validation.yml
使用验证器:
My\Bundle\Entity\Foo:
constraints:
- My\Bundle\Validator\Constraints\CheckTime: ~
这篇关于Symfony2 验证器约束大于其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!