Roo*_*eyl 6 php validation symfony
我的验证在yaml文件中定义,如此;
# 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]
Run Code Online (Sandbox Code Playgroud)
如何使用验证器约束GreaterThan来检查另一个属性?
例如,确保max_time大于min_time?
我知道我可以创建一个自定义约束验证器,但你肯定可以使用GreaterThan约束来完成它.
希望我在这里遗漏一些非常简单的东西
小智 9
使用选项propertyPath尝试GreaterThan约束:
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Column(type="datetime", nullable=true)
* @Assert\DateTime()
* @Assert\GreaterThan(propertyPath="minTime")
*/
protected $maxTime;
Run Code Online (Sandbox Code Playgroud)
我建议您查看Custom validator,尤其是Class Constraint Validator。
我不会复制粘贴整个代码,只会复制粘贴您必须更改的部分。
定义验证器,min_time和max_time是您要检查的 2 个字段。
<?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;
}
}
Run Code Online (Sandbox Code Playgroud)
定义验证器:
<?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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用验证器:
My\Bundle\Entity\Foo:
constraints:
- My\Bundle\Validator\Constraints\CheckTime: ~
Run Code Online (Sandbox Code Playgroud)