Validator
The Validator class is Slenix's validation engine. It validates input data against a set of rules, supports piped rule syntax, custom error messages, and integrates directly with the Request object and helper functions.
Creating a Validator
Using the static factory (recommended)
use Slenix\Supports\Validation\Validator;
$validator = Validator::make($data, $rules, $messages);Using the constructor directly
$validator = new Validator($data, $rules, $messages);Both accept the same three arguments:
| Argument | Type | Description |
|---|---|---|
$data | array | The input data to validate (e.g. $request->all()) |
$rules | array | Field-keyed validation rules |
$messages | array | Optional custom error messages |
Defining Rules
Rules are defined as a key-value array where each key is a field name and the value is a pipe-separated string (or array) of rules.
$rules = [
'name' => 'required|string|min:2|max:100',
'email' => 'required|email|unique:users,email',
'age' => 'required|integer|between:18,99',
'password' => 'required|min:8|confirmed',
'website' => 'nullable|url',
];Rules can also be passed as an array:
'name' => ['required', 'string', 'min:2'],Running Validation
validate() — strict mode
Runs all rules and returns the validated data. Throws a ValidationException if any rule fails.
try {
$validated = $validator->validate();
// $validated contains only the fields that passed
} catch (ValidationException $e) {
$errors = $e->errors(); // ['field' => 'message', ...]
$first = $e->first(); // First error message as string
}passes() and fails()
Non-throwing alternatives, useful for conditional logic.
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 422);
}
if ($validator->passes()) {
// safe to proceed
}Retrieving Errors
$validator->errors(); // All errors as ['field' => 'message']
$validator->firstErrors(); // First error per field as ['field' => 'message']
$validator->first('email'); // First error for a specific field, or nullAccessing Validated Data
After a successful validate() call, only the fields that passed are accessible:
$validated = $validator->safe(); // All validated fields
$subset = $validator->only('name', 'email'); // Pick specific fields
$rest = $validator->except('password'); // Exclude specific fieldsIntegration with Request
The Request object exposes a validate() method that accepts required field names and checks if they are present and filled. For full rule-based validation, pass $request->all() to Validator::make():
public function store(Request $request): void
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'age' => 'required|integer|min:18',
]);
if ($validator->fails()) {
// handle errors
}
$data = $validator->safe();
}Custom Error Messages
Override any default message by passing a messages array using the field.rule key format.
$messages = [
'email.required' => 'We need your email address.',
'email.email' => 'That does not look like a valid email.',
'age.min' => 'You must be at least 18 years old.',
];
$validator = Validator::make($data, $rules, $messages);Available Rules
Presence & Type
| Rule | Description |
|---|---|
required | Field must be present and non-empty |
nullable | Field may be null or empty — skips all other rules if so |
string | Must be a string |
integer | Must be an integer (validated via filter_var) |
float | Must be a decimal number |
boolean | Must be true, false, 0, 1, '0', '1', 'true', or 'false' |
array | Must be a PHP array |
numeric | Must be numeric (integers, floats, numeric strings) |
Format
| Rule | Description |
|---|---|
email | Must be a valid email address |
url | Must be a valid URL |
ip | Must be a valid IPv4 or IPv6 address |
uuid | Must be a valid UUID v4 |
date | Must be a parseable date string |
alpha | Must contain only alphabetic characters |
alpha_num | Must contain only letters and numbers |
regex:pattern | Must match the given regular expression |
Size & Range
| Rule | Description |
|---|---|
min:value | Minimum length (strings/arrays) or minimum value (numbers) |
max:value | Maximum length (strings/arrays) or maximum value (numbers) |
between:min,max | Length or value must fall within the given range |
size:value | Exact length (strings/arrays) or exact value (numbers) |
Allowed Values
| Rule | Description |
|---|---|
in:a,b,c | Value must be one of the given options |
not_in:a,b,c | Value must not be any of the given options |
Confirmation
| Rule | Description |
|---|---|
confirmed | Field must match a {field}_confirmation field in the data |
// Example: password and password_confirmation must match
'password' => 'required|confirmed',Database
These rules require a configured database connection via Slenix\Database\Connection.
| Rule | Syntax | Description |
|---|---|---|
unique | unique:table,column,ignoreId | Value must not already exist in the table |
exists | exists:table,column | Value must already exist in the table |
// On create — value must not exist
'email' => 'required|email|unique:users,email',
// On update — ignore the current record's ID
'email' => 'required|email|unique:users,email,' . $user->id,
// Value must reference an existing record
'category_id' => 'required|integer|exists:categories,id',Nested Fields (Dot Notation)
Fields within nested arrays can be validated using dot notation:
$data = [
'address' => [
'city' => 'Luanda',
'country' => 'AO',
],
];
$rules = [
'address.city' => 'required|string',
'address.country' => 'required|size:2',
];ValidationException
ValidationException is thrown by validate() when one or more rules fail.
use Slenix\Supports\Validation\ValidationException;
try {
$validated = $validator->validate();
} catch (ValidationException $e) {
$e->errors(); // ['field' => 'message', ...]
$e->first(); // First error message as a plain string
}Complete Example
use Slenix\Supports\Validation\Validator;
use Slenix\Supports\Validation\ValidationException;
public function register(Request $request, Response $response): void
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|min:2|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required|string',
'age' => 'required|integer|between:18,120',
'website' => 'nullable|url',
'role' => 'required|in:admin,editor,viewer',
], [
'email.unique' => 'This email address is already registered.',
'password.min' => 'Password must be at least 8 characters long.',
'age.between' => 'Age must be between 18 and 120.',
]);
if ($validator->fails()) {
return $response->status(422)->json([
'errors' => $validator->errors(),
]);
}
$data = $validator->except('password_confirmation');
// Proceed with $data — all fields are validated and safe
User::create($data);
return $response->status(201)->json(['message' => 'Account created.']);
}