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.
Great! Can it be used with embedded objects? Like @Assert\GreaterThan(propertyPath="category.startDate") ?
@Boldizsár yes, you can target embedded properties too. I've just updated the blog post to mention that. Thanks!
Finally! Redoing date validation constraints on every project comes to an end. Never liked the expression constraint.
Well, it will serve.