symfonysymfony5symfony-validator

symfony 5.4 validation constraints with groups are ignored


This annotation of a constraint works:

use App\Api\Dto\DtoInterface;
use Nelmio\ApiDocBundle\Annotation\Model;
use OpenApi\Annotations as OA;
use Symfony\Component\Serializer\Annotation\Groups as SerializerGroups;
use Symfony\Component\Validator\Constraints as Assert;


    class Report implements DtoInterface
    {
    
        /**
         * @OA\Property(description="visited house id SAP format 4 character string", type="string")
         *
         * @SerializerGroups({"create", "update", "view", "collection"})
         *
         * @Assert\NotBlank
         * @Assert\Length(4)
         */
        public string $house = '';

and this doesn't

use App\Api\Dto\DtoInterface;
use Nelmio\ApiDocBundle\Annotation\Model;
use OpenApi\Annotations as OA;
use Symfony\Component\Serializer\Annotation\Groups as SerializerGroups;
use Symfony\Component\Validator\Constraints as Assert;


    class Report implements DtoInterface
    {
    
        /**
         * @OA\Property(description="visited house id SAP format 4 character string", type="string")
         *
         * @SerializerGroups({"create", "update", "view", "collection"})
         *
         * @Assert\NotBlank(groups={"create", "update"})
         * @Assert\Length(min=4, groups={"create", "update"})
         */
        public string $house = '';

Lucky for me in this case ignoring groups will still work out for me, but in other cases it might not.

The Symfony documentation says that this is how it should work.

What is wrong with my second example? Why are those validators ignored?


Solution

  • Please note that in the second detection, @Assert\NotBlank(groups={"create", "update"}) sterilization groups were detected in the validators, in contrast to the first example, which means that they are presented only to the given groups, and all other requests with unspecified loads are ignored.

    In other words, the restrictions in the second example will only work for create and update, and for the view and collection groups they will be ignored, since they are not specified in the annotations.