首页 > 解决方案 > 当数据在 Symfony 中作为数组传递时,如何在验证组件中使用 EqualTo 约束?

问题描述

Symfony 提供了根据https://symfony.com/doc/current/validation/raw_values.html验证数组的方法,并使用它我想使用 EqualTo 约束(https://symfony.com/doc/current/reference/constraints /EqualTo.html ) 不使用密码并确认密码大小写。请看下面的代码:

$this->constraint = new Assert\Collection([
        // the keys correspond to the keys in the input array
        'fields' => [
            'password' =>
                [
                    new Assert\NotBlank(['message' => 'Please enter password.']),
                    new Assert\Length(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
                ]
            ,
            'confirm_password' =>
                [
                    new Assert\NotBlank(['message' => 'Please enter confirm password.']),
                    new Assert\EqualTo(['propertyPath' => 'password']),
                ]
            ,
        ],
        'allowMissingFields' => false,
        'missingFieldsMessage' => 'Please enter value.',
    ]);

现在,调用它:

$this->validator = Validation::createValidator();
$this->validator->validate($input, $this->constraint, $groups);

以上不起作用。

这个想法是在准备实体之前首先验证请求的数据,然后适当地持久化实体。另外,我想将验证机制与不同的实体分开。

标签: symfony

解决方案


而不是 EqualsTo 使用回调约束

        $this->constraint = new Assert\Collection([
        // the keys correspond to the keys in the input array
        'fields' => [
            'password' =>
                [
                    new Assert\NotBlank(['message' => 'Please enter password.']),
                    new Assert\Length(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
                ]
            ,
            'confirm_password' =>
                [
                    new Assert\NotBlank(['message' => 'Please enter confirm password.']),
                    new Assert\Callback(['callback' => function ($value, ExecutionContext $ec) {
                        if ($ec->getRoot()['password'] !== $value) {
                            $ec->addViolation("Passwords do not match");
                        }
                    }])
                ]
            ,
        ],
        'allowMissingFields' => false,
        'missingFieldsMessage' => 'Please enter value.',
    ]);

推荐阅读