New in Symfony 4.2: DivisibleBy 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
Colin O'Dell
in #28069.
In Symfony 4.2, the Validator component has introduced a new DivisibleBy
constraint to check whether one number is a multiple of ("divisible by") some
other number. It's mostly useful for enforcing specific increments on a number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// src/Entity/Item.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Item
{
/**
* @Assert\DivisibleBy(0.25)
*/
protected $weight;
/**
* @Assert\DivisibleBy(
* value = 5,
* message = "This item requires to be stocked in multiples of 5 units."
* )
*/
protected $quantity;
}
These constraints ensure that the weight
of the Item
is provided in
increments of 0.25
(e.g. 0.75
and 4.50
would be correct, but
0.18
or 7.32
wouldn't) and the quantity
must be divisible by 5
(25
and 22620
would be correct but 12
or 123456
wouldn't).
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.
Of course but the result a float, not what is expected.