respect-validation/docs/02-feature-guide.md
Henrique Moody 8e77021ce7
Reformat documentation files
There was some inconsistent Markdown, and some links were out of sync.
2025-12-27 17:03:25 +01:00

3.8 KiB
Raw Blame History

Feature Guide

The Validator class is the core of Respect\Validation, offering a fluent interface for building validation rules.

For convenience, the Validator class is aliased as v. This means you can write v::intType() instead of \Respect\Validation\Validator::intType().

Validating using booleans

With the isValid() method, determine if your input meets a specific validation rule.

if (v::intType()->positive()->isValid($input)) {
    echo 'The input you gave me is a positive integer';
} else {
    echo 'The input you gave me is not a positive integer';
}

Note that you can combine multiple rules for a complex validation.

Validating using exceptions

The assert() method throws an exception when validation fails. You can handle those exceptions with try/catch for more robust error handling.

Basic example

v::intType()->positive()->assert($input);

Smart validation

Respect\Validation offers over 150 rules, many of which are designed to address common scenarios. Heres a quick guide to some specific use cases and the rules that make validation straightforward.

Custom templates

Define your own error message when the validation fails:

v::between(1, 256)->assert($input, '{{subject}} is not what I was expecting');

Custom templates per rule

Provide unique messages for each rule in a chain:

v::alnum()->lowercase()->assert($input, [
    'alnum' => 'Your username must contain only letters and digits',
    'lowercase' => 'Your username must be lowercase',
]);

Custom exception objects

Integrate your own exception objects when the validation fails:

v::alnum()->assert($input, new DomainException('Not a valid username'));

Custom exception objects via callable

Provide a callable that creates an exception object to be used when the validation fails:

use Respect\Validation\Validator as v;
use Respect\Validation\Exceptions\ValidationException;

v::alnum()->lowercase()->assert(
    $input,
    fn(ValidationException $exception) => new DomainException('Username: '. $exception->getMessage()
);

Inverting validation rules

Use the not prefix to invert a validation rule.

v::notEquals('main')->assert($input);

For more details, check the Not rule documentation.

Reusing validators

Validators can be created once and reused across multiple inputs.

$validator = v::alnum()->lowercase();

$validator->assert('respect');
$validator->assert('validation');
$validator->assert('alexandre gaigalas');

Customising validator names

Template messages include the placeholder {{subject}}, which defaults to the input. Use setName() to replace it with a more descriptive label.

v::dateTime('Y-m-d')
    ->between('1980-02-02', 'now')
    ->setName('Age')
    ->assert($input);