> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Request Validation

> The `RequestValidationMiddleware` is a core component of Apivalk's Documentation-Driven Development approach. It ensures that every request hitting your controller strictly adheres to the schema defined in your `ApivalkRequestDocumentation`.

## How it Works

The middleware intercepts the request before it reaches the controller and performs the following steps:

1. **Extract Runtime Documentation**: It retrieves the **merged** documentation from `$request->getRuntimeDocumentation()` — the developer-declared properties plus route-derived metadata (filters, pagination params, available sort fields).
2. **Property Validation**: It iterates Body, Query, and Path properties and checks each corresponding value in the `ParameterBag` — running all validators attached to the property (`StringValidator`, `IntegerValidator`, `EnumValidator`, ...).
3. **Required Field Check**: If a property is marked `required` but missing, a validation error is recorded.
4. **Filter Validation**: Each filter in `$request->filtering()` is validated against its underlying property (required / type / custom validators).
5. **Sort Field Validation**: Each `Sort` in `$request->sorting()` must correspond to a field declared on the route via `Route::sorting([...])`. Unknown fields sent via `?order_by=...` produce a validation error (key `order_by`, message `Invalid sort field "X"`). Routes without declared sortings skip this check.
6. **Error Collection**: All errors are collected into `ValidationErrorObject[]`.

## 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 a `BadValidationApivalkResponse` (HTTP 422 Unprocessable Entity).

### Example Error Response

```json theme={null}
{
    "status": "error",
    "message": "Validation failed",
    "errors": [
        {
            "property": "email",
            "message": "Value is not a valid email address"
        },
        {
            "property": "age",
            "message": "Field is required"
        }
    ]
}
```

## 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.

## Usage

Enable the middleware in your configuration:

```php theme={null}
use apivalk\apivalk\Middleware\RequestValidationMiddleware;

$configuration->addMiddleware(new RequestValidationMiddleware());
```
