Skip to content

[Validator] AtLeastOneOf wrong behavior with groups #46638

Closed
@denissolomkin

Description

@denissolomkin

Symfony version(s) affected

5.4

Description

If you have several validation groups, you get unexpected behavior, validation not working

class AtLeastOneOfValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {

        ...

        foreach ($constraint->constraints as $key => $item) {

            // validator will be skipped, because group is different, violations will be empty, and validation will be passed without check 
            $violations = $validator->inContext($executionContext)->validate($value, $item, $this->context->getGroup())->getViolations();

            if (\count($this->context->getViolations()) === \count($violations)) {
                return;
            }

           ...

        }
    }
}

How to reproduce

First, run "composer require symfony/validator"
Then, execute this file:

<?php
require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;

$age = 60;
$constraints = [
    new Assert\AtLeastOneOf([
        new Assert\Blank(),
        new Assert\Range(
            min: 18,
            max: 55,
            groups: ['adult']
        ),
    ]),
];

$validator = Validation::createValidator();
$violations = $validator->validate($age, $constraints, groups: ['Default', 'adult']);

echo(sprintf('count: %d, violations: %s',count($violations), $violations));

Expected: Failed violation, because 60 > 55, but validation is passed

Possible Solution

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions