Description
Description
Symfony already provides several attributes to validate and handle requests before controller execution. However, this feature proposes a new attribute #[ValidateWith]
to give developers a flexible way to validate incoming requests using custom logic before executing.
By simply attaching #[ValidateWith(YourValidator::class)]
to a controller or route, Symfony would run the specified validator class, which must implement a new interface called RequestValidatorInterface
(not yet created). If the validation fails, the request can be interrupted by throwing an exception (e.g., with a custom status code).
This enables reusable, centralized request validation across routes, while keeping controllers clean and declarative.
Example
#[ValidateWith(BusinessRuleValidator::class)] // Defaults to 404 if validation fails
public function someAction(): Response
#[ValidateWith(ProjectOwnershipValidator::class, validationFailedStatusCode: 403)] // Custom failure code
public function restrictedAction(): Response
We can also define a custom page to redirect to in case of a validation failure.
#[ValidateWith(OtherValidator::class, redirectOnFailure: 'route_name')] // Redirect to the 'route_name' route if validation fails
public function otherAction(): Response