Symfony / Validator:Callback中的属性验证

时间:2023-01-15 11:09:03

I'm trying to create an Address entity with postal code validated based on the given country. The way to go is oviously the CallbackValidator. For now I have this code:

我正在尝试使用基于给定国家/地区验证的邮政编码创建一个地址实体。要走的路就是CallbackValidator。现在我有这个代码:

use SLLH\IsoCodesValidator\Constraints\ZipCode;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Address
{
    /**
     * @Callback()
     */
    public function validatePostalCode(ExecutionContextInterface $context)
    {
        $constraint = new ZipCode([ 'country' => $this->country ]);
        $violations = $context->getValidator()->validate($this->postalCode, $constraint);

        foreach ($violations as $violation) {
            $context->getViolations()->add($violation);
        }
    }
}

The problem with this is that the violations don't have correct path. I don't know how to set it though. Also $context->buildViolation($violation->getMessage()) is not good because I'd have to manually copy all the properties the violation might have.

这样做的问题是违规行为没有正确的路径。我不知道怎么设置它。 $ context-> buildViolation($ violation-> getMessage())也不好,因为我必须手动复制违规可能具有的所有属性。

EDIT: I've tried it and it is indeed very ugly.

编辑:我已经尝试过它确实非常难看。

1 个解决方案

#1


1  

This seems to work. The point is that you can actually specify the validation path if you use the contextual validator. Also you don't need to duplicate the violations as they are added directly to the intended context.

这似乎有效。关键是如果使用上下文验证器,您实际上可以指定验证路径。此外,您不需要复制违规,因为它们会直接添加到预期的上下文中。

/**
 * @Callback()
 */
public function validatePostalCode(ExecutionContextInterface $context)
{
    $constraint = new ZipCode([ 'country' => $this->country ]);
    $validator = $context->getValidator()->inContext($context);
    $validator->atPath('postalCode')->validate($this->postalCode, $constraint, [Constraint::DEFAULT_GROUP]);
}

#1


1  

This seems to work. The point is that you can actually specify the validation path if you use the contextual validator. Also you don't need to duplicate the violations as they are added directly to the intended context.

这似乎有效。关键是如果使用上下文验证器,您实际上可以指定验证路径。此外,您不需要复制违规,因为它们会直接添加到预期的上下文中。

/**
 * @Callback()
 */
public function validatePostalCode(ExecutionContextInterface $context)
{
    $constraint = new ZipCode([ 'country' => $this->country ]);
    $validator = $context->getValidator()->inContext($context);
    $validator->atPath('postalCode')->validate($this->postalCode, $constraint, [Constraint::DEFAULT_GROUP]);
}