New in Symfony 4.3: Number constraints
April 26, 2019 • 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
Jan Schädlich
in #28637.
The Symfony Validator component was originally based on the Java JSR-303 Bean Validation specification. While reviewing the Bean Validation 2.0 (JSR 380) specification, we found some new constraints that could be useful for Symfony applications.
That's why in Symfony 4.3 we've added four new constraints related to numbers:
Positive
, PositiveOrZero
, Negative
and NegativeOrZero
. Although
you could already validate that a number is positive/negative with the comparison
constraints (GreaterThan
, LessThanOrEqual
, etc.) these new constraints
will make your code easier to read and understand:
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 31 32 33
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
/** @Assert\PositiveOrZero */
protected $siblings;
// ...
}
class Employee
{
/** @Assert\Positive */
protected $income;
// ...
}
class UnderGroundGarage
{
/** @Assert\NegativeOrZero */
protected $level;
// ...
}
class TransferItem
{
/** @Assert\Negative */
protected $withdraw;
// ...
}
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.