Using the Symfony Validator, I can create a Compound constraint by inheritance:

// source: https://symfony.com/doc/current/reference/constraints/Compound.html
// src/Validator/Constraints/PasswordRequirements.php
namespace App\Validator\Constraints;

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

#[\Attribute]
class PasswordRequirements extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new Assert\NotBlank(),
            new Assert\Type('string'),
            new Assert\Length(['min' => 12]),
            new Assert\NotCompromisedPassword(),
        ];
   }
}

In alternate cases, I could also use Assert\Sequence to create a compound constraint that stops at the first validation error:

new Assert\Required( [
    new Assert\NotNull(),
    new Assert\NotBlank() // If the value is NULL, there is no need to check for blank
] );

The problem is, in both cases, I don't see a way to control the resulting validation error messages.

When using a Compound constraint, every validation error is returned. I would prefer to just have an over-arching error message, something like "Your password is not valid. Please make sure ... etc".

In the case of a Sequence, I would just like to return "This field is required." instead of different variations depending on what exactly went wrong (especially since the user really doesn't need to know the difference between null and "blank").

How can I return an over-arching custom error message for composite constraints like the above?

0

There are 0 best solutions below