Skip to content
Advertisement

Validate against several constraints with OR logic in Symfony

I have a field in a request which can either be email or phone. Now I need to validate it against two constraints – the standard email constraint and a custom phone. I know that I can pass an array of constrains link this:

$constraint = new ConstraintsCollection([
            'name' => new ConstraintsNotBlank(),
            'uid' => [new ConstraintsEmail(), new ConstraintsPhone()],
            'pass' => new ConstraintsNotBlank()
        ]);

But Validator applies the AND logic to the array of constraints, I need OR so that if the value fits one of them the validation succeeds. Is that possible by any standard Symfony means?

Advertisement

Answer

Create a custom validator and implement your own logic with existing constraint. AFAIK that’s no other way to obtain what you’re asking for.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement