繁体   English   中英

Symfony2 Validator Constraint GreaterThan on other property

[英]Symfony2 Validator Constraint GreaterThan on other property

我的验证在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]

如何使用验证器约束GreaterThan检查另一个属性?
例如,确保max_time大于min_time?

我知道我可以创建一个自定义约束验证器,但你肯定可以使用GreaterThan约束来完成它。
希望我在这里遗漏一些非常简单的东西

使用选项propertyPath尝试GreaterThan约束:

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Column(type="datetime", nullable=true)
 * @Assert\DateTime()
 * @Assert\GreaterThan(propertyPath="minTime")
 */
 protected $maxTime;

我建议你看一下Custom validator ,特别是Class Constraint Validator

我不会复制粘贴整个代码,只需要更改您需要更改的部分。

SRC /我/包\\型号\\富/识别/约束/ CheckTime.php

定义验证器, min_timemax_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;
    }
}

SRC /我/包/识别/约束/ 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 /我/包/资源/配置/ validation.yml

使用验证器:

My\Bundle\Entity\Foo:
    constraints:
        - My\Bundle\Validator\Constraints\CheckTime: ~

我建议你使用Callback验证器。 自定义验证器也可以工作,但如果这是一次性验证并且不会在应用程序的其他部分中重复使用,则可能是一种过度杀手。

使用回调验证器,您可以在同一个实体/模型上定义它们,并在类级别调用。

在你的情况下

// in your My\Bundle\Model\Foo:
/**
 * @Assert\Callback
 */
public function checkMaxTimeGreaterThanMin($foo, Constraint $constraint)
{
        if ($foo->getMinTime() > $foo->getMaxTime()) {
            $this->context->addViolationAt('max_time', $constraint->message, array(), null);
        }
}

或者如果你正在使用YAML

My\Bundle\Model\Foo:
    constraints:
        - Callback: [checkMaxTimeGreaterThanMin]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM