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

php
use Slenix\Supports\Validation\Validator;

$validator = Validator::make($data, $rules, $messages);

Using the constructor directly

php
$validator = new Validator($data, $rules, $messages);

Both accept the same three arguments:

ArgumentTypeDescription
$dataarrayThe input data to validate (e.g. $request->all())
$rulesarrayField-keyed validation rules
$messagesarrayOptional 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.

php
$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:

php
'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.

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

php
if ($validator->fails()) {
    return response()->json(['errors' => $validator->errors()], 422);
}

if ($validator->passes()) {
    // safe to proceed
}

Retrieving Errors

php
$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 null

Accessing Validated Data

After a successful validate() call, only the fields that passed are accessible:

php
$validated = $validator->safe();          // All validated fields
$subset    = $validator->only('name', 'email'); // Pick specific fields
$rest      = $validator->except('password');    // Exclude specific fields

Integration 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():

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

php
$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

RuleDescription
requiredField must be present and non-empty
nullableField may be null or empty — skips all other rules if so
stringMust be a string
integerMust be an integer (validated via filter_var)
floatMust be a decimal number
booleanMust be true, false, 0, 1, '0', '1', 'true', or 'false'
arrayMust be a PHP array
numericMust be numeric (integers, floats, numeric strings)

Format

RuleDescription
emailMust be a valid email address
urlMust be a valid URL
ipMust be a valid IPv4 or IPv6 address
uuidMust be a valid UUID v4
dateMust be a parseable date string
alphaMust contain only alphabetic characters
alpha_numMust contain only letters and numbers
regex:patternMust match the given regular expression

Size & Range

RuleDescription
min:valueMinimum length (strings/arrays) or minimum value (numbers)
max:valueMaximum length (strings/arrays) or maximum value (numbers)
between:min,maxLength or value must fall within the given range
size:valueExact length (strings/arrays) or exact value (numbers)

Allowed Values

RuleDescription
in:a,b,cValue must be one of the given options
not_in:a,b,cValue must not be any of the given options

Confirmation

RuleDescription
confirmedField must match a {field}_confirmation field in the data
php
// Example: password and password_confirmation must match
'password' => 'required|confirmed',

Database

These rules require a configured database connection via Slenix\Database\Connection.

RuleSyntaxDescription
uniqueunique:table,column,ignoreIdValue must not already exist in the table
existsexists:table,columnValue must already exist in the table
php
// 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:

php
$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.

php
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

php
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.']);
}