跳到内容

如何验证原始值(标量值和数组)

编辑此页

通常您将验证整个对象。但有时,您只想验证一个简单的值 - 例如验证一个字符串是否是有效的电子邮件地址。在控制器内部,它看起来像这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...
public function addEmail(string $email, ValidatorInterface $validator): void
{
    $emailConstraint = new Assert\Email();
    // all constraint "options" can be set this way
    $emailConstraint->message = 'Invalid email address';

    // use the validator to validate the value
    $errors = $validator->validate(
        $email,
        $emailConstraint
    );

    if (!$errors->count()) {
        // ... this IS a valid email address, do something
    } else {
        // this is *not* a valid email address
        $errorMessage = $errors[0]->getMessage();

        // ... do something with the error
    }

    // ...
}

通过在验证器上调用 validate(),您可以传入一个原始值和您想要针对该值进行验证的约束对象。完整的可用约束列表 - 以及每个约束的完整类名 - 可以在约束参考部分中找到。

可以使用 Collection 约束来验证数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidator();

$input = [
    'name' => [
        'first_name' => 'Fabien',
        'last_name' => 'Potencier',
    ],
    'email' => '[email protected]',
    'simple' => 'hello',
    'eye_color' => 3,
    'file' => null,
    'password' => 'test',
    'tags' => [
        [
            'slug' => 'symfony_doc',
            'label' => 'symfony doc',
        ],
    ],
];

$groups = new Assert\GroupSequence(['Default', 'custom']);

$constraint = new Assert\Collection([
    // the keys correspond to the keys in the input array
    'name' => new Assert\Collection([
        'first_name' => new Assert\Length(['min' => 101]),
        'last_name' => new Assert\Length(['min' => 1]),
    ]),
    'email' => new Assert\Email(),
    'simple' => new Assert\Length(['min' => 102]),
    'eye_color' => new Assert\Choice([3, 4]),
    'file' => new Assert\File(),
    'password' => new Assert\Length(['min' => 60]),
    'tags' => new Assert\Optional([
        new Assert\Type('array'),
        new Assert\Count(['min' => 1]),
        new Assert\All([
            new Assert\Collection([
                'slug' => [
                    new Assert\NotBlank(),
                    new Assert\Type(['type' => 'string']),
                ],
                'label' => [
                    new Assert\NotBlank(),
                ],
            ]),
            new CustomUniqueTagValidator(['groups' => 'custom']),
        ]),
    ]),
]);

$violations = $validator->validate($input, $constraint, $groups);

validate() 方法返回一个 ConstraintViolationList 对象,它类似于错误数组。集合中的每个错误都是一个 ConstraintViolation 对象,该对象在其 getMessage() 方法中保存错误消息。

注意

当将组与 Collection 约束一起使用时,请务必在适当时使用 Optional 约束,如其参考文档中所述。

这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可证获得许可。
目录
    版本