Validation
Never trust input. Nimbus gives you three ways to validate it, all producing the same 422 error response:
- Form requests use Laravel’s rule syntax (
'required|email|max:255'). They are the fastest way to port an existing Laravel API and handle nested data and wildcards. - Typed inputs are classes whose public properties are the accepted fields. PHP types and attributes such as
#[Max(120)]are the rules, and the controller receives a fully typed object. - The
Validatorvalidates any array on demand, for queued payloads or webhook bodies.
Form requests and typed inputs are resolved and validated before your controller runs, so the action only ever sees valid data.
Validation Quickstart
Section titled “Validation Quickstart”Define a form request with its rules:
<?php
declare(strict_types=1);
namespace App\Requests;
use Nimbus\Validation\FormRequest;
final class StoreProductRequest extends FormRequest{ public function rules(): array { return [ 'name' => 'required|string|max:120', 'price' => ['required', 'integer', 'min:1'], 'tags' => 'nullable|array', 'tags.*' => 'string|alpha_dash', ]; }
public function messages(): array { return ['price.min' => 'Prices are stored in cents and must be positive.']; }}Type-hint it in the action. When validation passes, validated() returns only the fields that have rules:
use App\Requests\StoreProductRequest;use App\Resources\ProductResource;
public function store(StoreProductRequest $request): ProductResource{ $product = $this->products->create($request->validated());
return new ProductResource($product, 201);}When it fails, Nimbus stops the request and answers 422 Unprocessable Entity with every error, keyed by field, in a Problem Details body:
$ curl -X POST http://127.0.0.1:3000/api/products -H 'content-type: application/json' \ -d '{"name":"","price":0,"tags":["ok","bad tag"]}'{ "errors": { "name": ["The name field is required."], "price": ["Prices are stored in cents and must be positive."], "tags.1": ["The tags.1 field must only contain letters, numbers, dashes, and underscores."] }, "type": "https://pam.dev/problems/1", "title": "The submitted data is invalid.", "status": 422, "code": 1}Form Requests
Section titled “Form Requests”Where the Data Comes From
Section titled “Where the Data Comes From”A form request validates the query string merged with the body; when both have the same key, the body wins. The body is read according to its content-type:
application/json(or no content type): a JSON object;application/x-www-form-urlencodedandmultipart/form-data: the text fields.
A JSON body that is not an object fails with an error on body. Values that arrive as strings (query string, form fields) are cast when the rule is integer, numeric or boolean, so "3" with integer is validated and returned as 3.
Nested Data and Wildcards
Section titled “Nested Data and Wildcards”Use dot notation for nested objects and * for every element of a list. Errors are reported under the concrete path:
<?php
declare(strict_types=1);
namespace App\Requests;
use App\Enums\Shipping;use App\Rules\Uppercase;use Nimbus\Validation\FormRequest;use Nimbus\Validation\Rule;
final class StoreOrderRequest extends FormRequest{ public function rules(): array { return [ 'customer.email' => 'required|email', 'coupon' => ['nullable', 'string', new Uppercase()], 'shipping' => ['required', Rule::enum(Shipping::class)], 'items' => 'required|array|min:1', 'items.*.sku' => 'required|string|alpha_dash', 'items.*.quantity' => 'required|integer|between:1,99', 'notes' => 'sometimes|string|max:500', ]; }
public function attributes(): array { return ['customer.email' => 'e-mail address']; }}$ curl -X POST http://127.0.0.1:3000/orders -H 'content-type: application/json' -d '{ "customer": {"email": "x"}, "coupon": "save10", "shipping": "drone", "items": [{"sku": "KB-1", "quantity": "3"}, {"sku": "bad sku", "quantity": 120}] }'{ "errors": { "customer.email": ["The e-mail address field must be a valid email address."], "coupon": ["The coupon field must be uppercase."], "shipping": ["The shipping field is invalid."], "items.1.sku": ["The items.1.sku field must only contain letters, numbers, dashes, and underscores."], "items.1.quantity": ["The items.1.quantity field must be between 1 and 99."] }, "type": "https://pam.dev/problems/1", "title": "The submitted data is invalid.", "status": 422, "code": 1}With valid data, unknown fields are dropped and cast values are returned:
{"customer":{"email":"[email protected]"},"coupon":"SAVE10","shipping":"express","items":[{"sku":"KB-1","quantity":3}]}Customizing Messages and Attribute Names
Section titled “Customizing Messages and Attribute Names”messages() overrides messages by field.rule, by field or by rule (wildcards allowed). attributes() renames fields inside messages. Messages support the placeholders :attribute, :value, :min, :max, :size, :values, :other, :date and :format:
public function messages(): array{ return [ 'items.*.sku.exists' => 'Unknown product :value.', 'required' => 'Please fill in :attribute.', ];}Authorizing Form Requests
Section titled “Authorizing Form Requests”Return false from authorize() to reject the request with 403 before any rule runs. The form request can read the request through $this->request:
public function authorize(): bool{ return $this->request->getHeader('x-role') === 'admin';}Working With Validated Data
Section titled “Working With Validated Data”| Method | Returns |
|---|---|
validated() |
Every validated field as an array. |
input(string $key, mixed $default = null) |
One validated top-level field. |
dto(string $class) |
The validated data hydrated into an object of your class. |
Typed Inputs
Section titled “Typed Inputs”A typed input is a class that extends Nimbus\Validation\Input. Its public properties are the accepted fields; their PHP types are enforced and attributes add rules. Generate one with the CLI:
pam make:request CreateInvite<?php
declare(strict_types=1);
namespace App\Requests;
use Nimbus\Validation\Attributes\Email;use Nimbus\Validation\Attributes\Field;use Nimbus\Validation\Attributes\In;use Nimbus\Validation\Attributes\Max;use Nimbus\Validation\Input;
final class CreateInvite extends Input{ #[Email, Max(255)] public string $email;
#[In('member', 'admin')] public string $role = 'member';
#[Field('expires_in_days'), Max(30)] public ?int $expiresInDays = null;}use App\Requests\CreateInvite;
$router->post('/invites', fn (CreateInvite $invite) => $invite->toArray());$ curl -X POST http://127.0.0.1:3000/invites -H 'content-type: application/json' \
$ curl -X POST http://127.0.0.1:3000/invites -H 'content-type: application/json' \ -d '{"email":"nope","role":"owner","expires_in_days":90}'{"errors":{"email":["The email field must be a valid email address."],"role":["The role field must be one of: member, admin."],"expires_in_days":["The expires_in_days field must be at most 30."]},"type":"https:\/\/pam.dev\/problems\/1","title":"The submitted data is invalid.","status":422,"code":1}The rules come from the class itself:
- A property without a default is required, unless its type is nullable.
- The type is enforced:
string,int,float,bool,array, a backed enum,DateTimeImmutable(ISO 8601), or anotherInputfor a nested object. Numeric strings are accepted forintandfloat, and"true","false","1"and"0"forbool. - Attributes add rules:
#[Email],#[Url](http and https only),#[Uuid],#[Regex('/^[A-Z]+$/')],#[In(...)],#[Min(n)]and#[Max(n)](a number, a string length, or an item count). #[Field('name')]reads the property from a differently named key.- Properties cannot be
readonly, because Nimbus fills them after validation.
GET, HEAD and DELETE requests read the input from the query string; other methods read the JSON object body, or the form fields of urlencoded and multipart bodies.
Typed inputs also offer:
| Member | Description |
|---|---|
authorize(Request $request): bool |
Override to reject with 403. |
Input::from(array $data) |
Build and validate from an array, such as a queued payload. |
toArray() |
The validated values keyed by property; enums become their value and dates ISO 8601 strings. |
Input::schema() |
The JSON Schema of the fields, used for the OpenAPI document. |
'email' => ['required', 'email', 'max:255'],'role' => ['nullable', Rule::in(['member', 'admin'])],Best for porting Laravel code, nested arrays and wildcards.
#[Email, Max(255)] public string $email;#[In('member', 'admin')] public string $role = 'member';Best for new endpoints: typed properties, IDE completion, and an exact OpenAPI schema.
Manually Creating Validators
Section titled “Manually Creating Validators”Use Nimbus\Validation\Validator to validate any array with the same rules as form requests:
use Nimbus\Validation\Validator;use Pam\Http\Request;
$router->get('/report', function (Request $request): array { $validator = Validator::make($request->query(), [ 'from' => 'required|date', 'hours' => 'nullable|integer|between:1,720', ]);
if ($validator->fails()) { return ['errors' => $validator->errors()]; }
return $validator->validated();});$ curl 'http://127.0.0.1:3000/report?from=2026-01-01&hours=24'{"from":"2026-01-01","hours":24}$ curl 'http://127.0.0.1:3000/report?hours=x'{"errors":{"from":["The from field is required."],"hours":["The hours field must be an integer."]}}validate() returns the validated data or throws Nimbus\Validation\ValidationException, which Nimbus renders as the standard 422 response. Validator::make() also accepts custom messages and attribute names as its third and fourth arguments.
Available Validation Rules
Section titled “Available Validation Rules”| Rule | Passes when the value… |
|---|---|
accepted |
is yes, on, 1, true. |
after:date, after_or_equal:date, before:date, before_or_equal:date |
is a date after or before another date (or another field). |
alpha, alpha_num, alpha_dash |
contains only letters; letters and numbers; or also dashes and underscores. |
array, list |
is an array; or a list (sequential keys). |
between:min,max, min:value, max:value, size:value |
has a size in range: a number’s value, a string’s length, an array’s count. |
boolean |
is true, false, 1, 0, "1", "0", "true", "false". |
confirmed |
matches the {field}_confirmation field. |
date, date_format:format |
is a valid date; or matches the format. |
different:field, same:field |
differs from, or equals, another field. |
digits:n |
is made of exactly n digits. |
email, url, uuid, ip, json |
is a valid e-mail, URL, UUID, IP address, or JSON string. |
exists:table,column, unique:table,column |
exists, or does not exist, in the database. |
filled |
is not empty when present. |
in:a,b, not_in:a,b |
is, or is not, one of the values. |
integer, numeric, string |
has the type. |
present |
is present, even if empty. |
regex:pattern, not_regex:pattern |
matches, or does not match, the pattern. |
required |
is present and not empty. |
required_if:field,value, required_unless:field,value |
is present when another field has, or lacks, a value. |
required_with:fields, required_without:fields |
is present when other fields are, or are not, present. |
Three modifiers change how the rules run: nullable (a null value passes), sometimes (validate only when the key is present) and bail (stop at the first failure of the field). An unknown rule name throws InvalidArgumentException, so typos fail loudly in development.
Rule Objects
Section titled “Rule Objects”Nimbus\Validation\Rule builds rules with arguments that are awkward in strings:
use Nimbus\Validation\Rule;
'status' => ['required', Rule::enum(OrderStatus::class)],'plan' => ['required', Rule::in(['free', 'pro'])],'country' => [Rule::notIn(['XX'])],'sku' => ['required', Rule::exists('products', 'sku')],'email' => ['required', Rule::unique('users', 'email')->ignore($userId)],exists and unique query the database through a presence verifier. Registering Nimbus\Database\ArcanoServiceProvider sets one up; without it, these rules throw a LogicException explaining what to register. See Database.
Custom Validation Rules
Section titled “Custom Validation Rules”A custom rule implements Nimbus\Validation\ValidationRule. Return null when the value passes, or the error message. Add #[\Attribute] and the same class works as a typed-input attribute too:
<?php
declare(strict_types=1);
namespace App\Rules;
use Nimbus\Validation\ValidationRule;
#[\Attribute(\Attribute::TARGET_PROPERTY)]final readonly class Uppercase implements ValidationRule{ public function validate(string $field, mixed $value): ?string { return is_string($value) && mb_strtoupper($value) !== $value ? "The {$field} field must be uppercase." : null; }}// In a form request'coupon' => ['nullable', 'string', new Uppercase()],
// In a typed input#[Uppercase] public ?string $coupon = null;Error Format
Section titled “Error Format”Validation errors are a ValidationException (an HttpException with status 422 and problem code 1). The errors member maps each field path to a list of messages. If your clients expect Laravel’s {"message": ..., "errors": ...} body, switch the error renderer; see Error Handling.
Testing Validation
Section titled “Testing Validation”The in-memory test client has assertions for validation errors:
public function test_it_validates_new_products(): void{ $this->postJson('/api/products', ['name' => '', 'price' => 0]) ->assertUnprocessableEntity() ->assertJsonValidationErrors(['name', 'price']);}pam test