How it Works
The middleware intercepts the request before it reaches the controller and performs the following steps:- Extract Documentation: It retrieves the property definitions for Body, Query, and Path parameters from the Request object.
- Iterative Validation: It iterates through each defined property and checks the corresponding value in the
ParameterBag. - Required Field Check: If a property is marked as
requiredbut missing from the request, a validation error is recorded. - Validator Execution: If the value is present, it runs all validators attached to that property (e.g.,
StringValidator,NumberValidator,EnumValidator). - Error Collection: If any validation fails, the middleware collects the errors into an array of
ErrorObjectinstances.
Automatic Response
If one or more validation errors are found, the middleware short-circuits the request lifecycle. It does not call the next middleware or the controller. Instead, it immediately returns aBadValidationApivalkResponse (HTTP 422 Unprocessable Entity).
Example Error Response
Benefits
- Clean Controllers: Your controllers never need to contain validation logic. By the time they are executed, you are guaranteed that the input is valid and correctly typed.
- Consistency: Validation errors follow a standardized format across your entire API.
- Synchronized Docs: Since validation is driven by the documentation, your API’s behavior always matches what is described in your generated OpenAPI specification.