API Platform not applying validation using groups on POST requests

I am facing an issue with API Platform (using Symfony 6.4) where validations specified using validation groups are not being applied automatically during POST operations. Despite properly configuring annotations and serialization/deserialization groups, the validations are only triggered when I use a custom event subscriber.

Here is an excerpt from my Symfony entity:

<?php
#[ApiResource(
    operations: [
        new Post(
            uriTemplate: '',
            denormalizationContext: ['groups' => ['calibration_cards_write']],
            security: 'user.isCanDoVcas() === true',
            processor: CalibrationCardPostProcessor::class
        )
    ],
    routePrefix: '/calibration_cards',
    normalizationContext: ["groups" => ["calibration_cards_read"]],
    denormalizationContext: ["groups" => ["calibration_cards_write", 'calibration_cards_patch']]
)]
#[ORMEntity]
class CalibrationCard {
    #[ORMColumn(length: 255)]
    #[Groups(["calibration_cards_read", "calibration_cards_write"])]
    #[AssertNotBlank(message: "The 'name' field is required.", groups: ["calibration_cards_write"])]
    #[AssertRegex("/^[A-Za-zÀ-úœ'-s]+$/", message: "The 'name' field contains invalid characters.", groups: ["calibration_cards_write"])]
    private ?string $name = null;
}

Despite setting up everything correctly, when I send a POST request without the name field, the NotBlank validation does not trigger unless I manually invoke validation through an event subscriber in the API Platform lifecycle.

Interestingly, if I remove the groups from the AssertNotBlank annotation, the validation triggers correctly for POST requests. However, this causes an unwanted side effect: the NotBlank error also appears on PATCH routes where the name field is not supposed to be modified.

Here’s how I’ve set up my subscriber:

<?php
namespace AppEventSubscriber;

use ApiPlatformSymfonyEventListenerEventPriorities;
use AppEntityCalibrationCard;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentHttpKernelEventViewEvent;
use SymfonyComponentHttpKernelKernelEvents;
use SymfonyComponentValidatorValidatorValidatorInterface;

class ValidationSubscriber implements EventSubscriberInterface {
    private $validator;

    public function __construct(ValidatorInterface $validator) {
        this->validator = $validator;
    }

    public static function getSubscribedEvents() {
        return [KernelEvents::VIEW => ['validateEntity', EventPriorities::PRE_VALIDATE]];
    }

    public function validateEntity(ViewEvent $event) {
        $entity = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$entity instanceof CalibrationCard || $method !== 'POST') {
            return;
        }

        $errors = this->validator->validate($entity, null, ['calibration_cards_write']);
        if (count($errors) > 0) {
            dd($errors);
        }
    }
}

The validations work as expected when manually invoked (errors are dumped with the subscriber) but do not trigger automatically. Am I missing something in the API Platform configuration, or is there an issue with how validation groups are processed in the framework?

Any help or guidance would be greatly appreciated. Thank you in advance for your assistance!

New contributor

GeppettoG is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

You need to use a validation context instead of the denormalization context. See documentation chapter Using Validation Groups on Operations.

You may want to use sequential validation to chain multiple assertions and overcome potential issues here.

The AssertRegex assertion will throw an UnexpectedValueException if $name is not a string (i.e. null).

See the documentation chapter Sequentually

Example:

// src/Localization/Place.php
namespace AppLocalization;

use ApiPlatformMetadataApiResource;
use ApiPlatformMetadataPost;
use SymfonyComponentValidatorConstraints as Assert;

#[ApiResource]
#[Post(validationContext: ['groups' => ['calibration_cards_write']])]
class CalibrationCard
{
    #[AssertSequentially([
        new AssertNotNull,
        new AssertType('string'),
        new AssertLength(min: 10),
        new AssertRegex(CalibrationCard::NAME_REGEX),
      ], groups: [
        "calibration_cards_write"
      ]
    )]
    public ?string $name;
}

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật