Symfony验证-在自定义验证中设置属性路径
我想问一下,如何设置违反约束的属性路径 到目前为止,我正在做一个普通的验证,比如(其中用户是一个具有一些预定义约束的普通实体,这些约束作为aspected工作): 接下来,在user registration controller方法中,我尝试使用手动方法(因为将约束直接放在用户实体中会导致每次验证密码) 我在需要时验证密码,如下所示:Symfony验证-在自定义验证中设置属性路径,symfony,validation,constraints,Symfony,Validation,Constraints,我想问一下,如何设置违反约束的属性路径 到目前为止,我正在做一个普通的验证,比如(其中用户是一个具有一些预定义约束的普通实体,这些约束作为aspected工作): 接下来,在user registration controller方法中,我尝试使用手动方法(因为将约束直接放在用户实体中会导致每次验证密码) 我在需要时验证密码,如下所示: $passwordLength = mb_strlen($password); $passwordMinLength = new Assert\Length(n
$passwordLength = mb_strlen($password);
$passwordMinLength = new Assert\Length(null, 8);
$passwordErrors = $this->validator->validate($passwordLength, [ $passwordMinLength ]);
然后,我将结果添加到现有集合中:
$validationErrors->addAll($passwordErrors);
但是当我检查密码生成的冲突时,它没有定义propertyPath。我构建了一个自定义的细枝扩展,它依赖于所设置的propertypath。如何告诉它在$passwordErrors
数组上使用名为“password”的属性路径
我希望你能理解我的问题:)
致以最良好的祝愿
抢劫
编辑:
我找到了适合我工作的解决方案。我确信,这不是解决我问题的最佳方式,但由于我已经为这件小事浪费了几个小时,我决定选择解决办法,而不是在这件小事上花更多的时间
我的解决方案
虽然我无法访问私有属性propertyPath,但我想为每个违规设置propertyPath,因此我用以下方法解决了这个问题:
首先,我创建了一个闭包函数:
$closure = Closure::bind(function (ConstraintViolation $violation) {
$violation->propertyPath = 'password';
}, null, ConstraintViolation::class);
然后我对每一次违规都打了电话:
foreach ($passwordErrors as $violation) {
// $violation->propertyPath = 'password';
$closure($violation);
}
如果我理解正确,您需要一个类约束验证器。
您需要将其添加到约束类:
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
这样,验证器的validate()
方法将获取一个对象作为其第一个参数,atPath()
方法用于定义与验证错误关联的属性
class ProtocolClassValidator extends ConstraintValidator
{
public function validate($protocol, Constraint $constraint)
{
if ($protocol->getFoo() != $protocol->getBar()) {
$this->context->buildViolation($constraint->message)
->atPath('foo')
->addViolation();
}
}
}
文档:我刚刚发现如何修改现有的违规行为 而不是使用
$validationErrors->addAll($passwordErrors);
在自定义验证器中,使用
/**@var ConstraintViolationInterface$冲突*/
foreach($validationErrors作为$violation){
$this->context->buildViolation($violation->getMessage())
->atPath('密码')
->添加违例();
}
class ProtocolClassValidator extends ConstraintValidator
{
public function validate($protocol, Constraint $constraint)
{
if ($protocol->getFoo() != $protocol->getBar()) {
$this->context->buildViolation($constraint->message)
->atPath('foo')
->addViolation();
}
}
}