The Valid constraint enables validation on objects that are embedded as properties on the object being validated. This allows you to validate an object and all sub-objects associated with it. For example, validate the Address object embedded in an Author object:
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;
}
The main shortcoming of this constraint it that it doesn't support validation groups. In Symfony 3.4, we improved the Valid constraint to add support for groups:
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;
}
In the previous example, the Valid
constraint only validates the properties
that belong to the basic
group in the Address
object, so it will only
validate the street
property and not the zipCode
property.
Great job!
Great job ! thank you so much !!
Oh yeah!
Yeaaah. Thanks