Contributed by
Christian Flothmann
in #21111.

Valid constraint(Valid约束),能够对“作为被验证对象之属性”的对象进行验证。这可令你验证一个对象,以及全部它所关联的子对象。例如,验证嵌在 Author 对象中的 Address 对象:

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
// src/AppBundle/Entity/Address.php
namespace AppBundle\Entity;
 
use Symfony\Component\Validator\Constraints as Assert;
 
class Address
{
    /** @Assert\NotBlank() */
    protected $street;
 
    /** @Assert\Length(max = 5) */
    protected $zipCode;
}
 
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
 
use Symfony\Component\Validator\Constraints as Assert;
 
class Author
{
    /** @Assert\NotBlank */
    protected $firstName;
 
    /** @Assert\NotBlank */
    protected $lastName;
 
    /** @Assert\Valid */
    protected $address;
}

这个约束的主要短板是,它不支持 validation groups 验证群组功能。在 Symfony 3.4 中,我们改进了Valid约束令其支持群组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/AppBundle/Entity/Address.php
// ...
class Address
{
    /** @Assert\NotBlank(groups={"basic"}) */
    protected $street;
 
    /** @Assert\Length(max = 5) */
    protected $zipCode;
}
 
// src/AppBundle/Entity/Author.php
// ...
class Author
{
    /** @Assert\NotBlank */
    protected $firstName;
 
    /** @Assert\NotBlank */
    protected $lastName;
 
    /** @Assert\Valid(groups={"basic"}) */
    protected $address;
}

上例中,Valid 只去验证 Address 对象中隶属于 basic 群组的属性,因此它只会验证 street 属性而不是 zipCode 属性。