New in Symfony 3.4: Improved comparison constraints
September 21, 2017 • Published by Javier Eguiluz
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
Maxime Steinhausser
in #22576.
The original purpose of comparison constraints was to validate properties against some predefined value (e.g. "the price must be greater than 0", "the age must be greater or equal than 18", etc.)
However, in Symfony applications is common to compare the value of object properties between them (e.g. "the end date is greater than the start date", "the plain password is not identical to the login", etc.)
In those cases, you can use the Expression constraint to define a expression that compares both properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Validator\Constraints as Assert;
class Event
{
/** @Assert\DateTime() */
private $startDate;
/**
* @Assert\DateTime()
* @Assert\Expression("value > this.startDate")
*/
private $endDate;
// ...
}
In Symfony 3.4, we improved the comparison expressions to accept a new option
called propertyPath
which defines the path of the property whose value you
want to compare with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Validator\Constraints as Assert;
class Event
{
/** @Assert\DateTime() */
private $startDate;
/**
* @Assert\DateTime()
* @Assert\GreaterThan(propertyPath="startDate")
*/
private $endDate;
// ...
}
The value of the propertyPath
option can be any valid PropertyAccess component
notation, so you can refer to properties of embedded objects too.
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 are closed.
To ensure that comments stay relevant, they are closed for old posts.