New in Symfony 3.4: Groups support for the Valid constraint
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Christian Flothmann
in #21111.
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.