实体验证 - 零或至少三

时间:2017-04-07 08:35:22

标签: symfony validation symfony-validator

我正在使用symfony 2.8版本,我遇到了以下问题。我希望实体'Article'的字段'seeAlso'被限制为零(无)或至少3个对象(另一篇文章)。所以我在我的yaml验证中有这些:

seeAlso:
 - Count:
   min: 3
   minMessage: 'you have got to pick zero or at least three articles'

它检查它是否小于三,但它不允许我让该字段为空。我如何使这项工作?

1 个答案:

答案 0 :(得分:4)

您应该定义自定义验证。您可以通过两种方式继续

1创建自定义验证约束

首先,您需要创建一个约束类

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ConstraintZeroOrAtLeastThreeConstraint extends Constraint
{
    public $message = 'Put here a validation error message';

    public function validatedBy()
    {
        return get_class($this).'Validator';
    }
}

在这里,您已经使用消息定义了约束,并且您告诉symfony哪个是验证器(我们将在下面定义)

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ZeroOrAtLeastThreeConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!count($value)) {
            return;
        }

        if (count($value) >= 3) {
            return;
        }

        $this
          ->context
          ->buildValidation('You should choose zero or at least three elements')
          ->addViolation();
    }
}

现在,您可以通过使用@ ConstraintZeroOrAtLeastThreeConstraint注释来在属性上使用验证器(当然,您必须在实体文件中导入才能使用)

当然,您甚至可以自定义值0和3,通过使用

将此约束推广到ZeroOrAtLeastTimesConstraint
public function __construct($options)
{
    if (!isset($options['atLeastTimes'])) {
        throw new MissingOptionException(...);
    }

    $this->atLeastTimes = $options['atLeastTimes'];
}

2在实体

中创建回调验证功能
/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context, $payload)
{
    if (!count($this->getArticles()) {
       return;
    }

    if (count($this->getArticles() >= 3) { 
       return;
    }

    $context
      ->buildViolation('You should choose 0 or at least 3 articles')
      ->addViolation();
}
相关问题