Przemysław Bogusz
Contributed by Przemysław Bogusz in #35744

In addition to the Hostname validator and the ExpressionLanguage validator, in Symfony 5.1 we've added another validator called AtLeastOneOf. You can apply it to methods and properties to ensure that their values satisfies at least one of the given constraints (which can be any of the built-in Symfony constraints and/or your own custom constraints):

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
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class SomeEntity
{
    /**
     * @Assert\AtLeastOneOf({
     *     @Assert\Length(min=5),
     *     @Assert\EqualTo("bar")
     * })
     */
    public $name = 'foo';

    /**
     * @Assert\AtLeastOneOf({
     *     @Assert\All({@Assert\GreaterThanOrEqual(10)}),
     *     @Assert\Count(20)
     * })
     */
    public $numbers = ['3', '5'];

    /**
     * @Assert\All({
     *     @Assert\AtLeastOneOf({
     *          @Assert\GreaterThanOrEqual(5),
     *          @Assert\LessThanOrEqual(3)
     *     })
     * })
     */
    public $otherNumbers = ['4', '5'];
}

By default, the error messages lists all the failed conditions:

1
2
3
4
5
6
7
8
9
10
11
name: This value should satisfy at least one of the following constraints:
[1] This value is too short. It should have 5 characters or more.
[2] This value should be equal to "bar".

numbers: This value should satisfy at least one of the following constraints:
[1] Each element of this collection should satisfy its own set of constraints.
[2] This collection should contain exactly 20 elements.

otherNumbers[0]: This value should satisfy at least one of the following constraints:
[1] This value should be greater than or equal to 5.
[2] This value should be less than or equal to 3.
Published in #Living on the edge