您应该定义一个自定义验证。您可以通过以下两种方式
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();
}
}
现在你可以在物业使用您的验证^ h @ ConstraintZeroOrAtLeastThreeConstraint
(那当然,你必须在实体文件导入才能使用)使用
public function __construct($options)
{
if (!isset($options['atLeastTimes'])) {
throw new MissingOptionException(...);
}
$this->atLeastTimes = $options['atLeastTimes'];
}
2创建
当然,你甚至可以自定义值0和3概括这个约束到ZeroOrAtLeastTimesConstraint
实体内部的回调验证功能
/**
* @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();
}
我想使用你的第一个方法,我有问题:1.我在哪里存储约束类? 2.我在哪里存储验证器? (第二个文件)3.我如何在我的财产中使用此验证器? 3.那么我应该把什么放在我的XML文件? – user7808407
@ user7808407答案1和2:你喜欢的地方,通常在'Validator \ Constraint'下约束和Validator''Validator'。答案3:在你的'yml'文件中,你可以像使用其他约束条件 – DonCallisto
一样使用它,谢谢澄清。所以我遵循所有步骤并得到了这个错误消息约束验证器“Symfony \ Component \ Validator \ Constraints \ ConstraintSeeAlsoConstraintValidator”不存在或未启用。检查约束类“Symfony \ Component \ Validator \ Constraints \ ConstraintSeeAlsoConstraint”中的“validatedBy”方法可能会出现什么问题? – user7808407