Docs LATEST

Validator Usage

Validate input in controllers and CLI.

Validation

Basic usage #

$validated = Validator::make($data, [
    'email' => 'required|email',
    'password' => 'min:8',
])->validate();

In controllers #

$validated = $request->validate([
    'title' => 'required|min:3',
    'status' => 'in:draft,published',
]);

Available rules #

Rule Description
required Field must be present and not empty
email Must be a valid email address
url Must be a valid URL
min:n Minimum length (string) or count (array)
max:n Maximum length (string) or count (array)
numeric Must be numeric
integer Must be an integer
boolean Must be true/false (or 0, 1, 'true', 'false')
alpha Only letters allowed
alphanumeric Only letters and numbers allowed
in:a,b,c Value must be in list
regex:/pattern/ Must match regex pattern
same:field Must match another field
different:field Must be different from another field
date Must be a valid date
array Must be an array

Handling errors #

Validation failures throw ValidationException with a structured errors array.

try {
    $validated = Validator::make($data, $rules)->validate();
} catch (ValidationException $e) {
    $errors = $e->errors(); // ['field' => ['Error message']]
}

Custom rules #

Register your own validation rules with Validator::extend():

use VelvetCMS\Validation\Validator;

// Register a 'slug' rule
Validator::extend('slug', function ($value, $parameter, $data, $field) {
    if (!preg_match('/^[a-z0-9-]+$/', $value)) {
        return "The {$field} must be a valid slug (lowercase, numbers, hyphens).";
    }
    return true;
});

// Use it like any built-in rule
$validated = Validator::make($data, [
    'url_slug' => 'required|slug',
])->validate();

The callback receives:

  • $value - the field value being validated
  • $parameter - parameter after : (e.g., '10' for custom:10)
  • $data - the full data array
  • $field - the field name

Return true if valid, false for a generic error, or a string for a custom message.