ZetCode

PHP Respect Validation

last modified November 14, 2026

PHP Respect Validation tutorial shows how to validate PHP values with the Respect Validation package. The examples were run with Respect Validation 3.1 and PHP 8.5.

Respect Validation

Respect Validation is a PHP standalone validation library. It has more than 150 validators, which can be chained with a fluent interface. A validator can check a single value, the keys of an array, or the properties of an object, and it can produce detailed error messages.

The 3.x series requires PHP 8.5 or newer and differs from the 2.x series that older tutorials describe:

Installation

We install the Respect Validation package with Composer. Some validators need optional packages; for instance, the uuid rule requires ramsey/uuid, and the library tells us so with an exception.

$ composer require respect/validation

Respect Validation simple example

In the first example, we show how to do a very simple validation.

simple.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$name = 'JohnDoe';

if (v::alnum()->isValid($name)) {
    echo "Validation passed\n";
} else {
    echo "Validation failed\n";
}

$name = 'John Doe';

if (v::alnum()->isValid($name)) {
    echo "Validation passed\n";
} else {
    echo "Validation failed\n";
}

The example validates two values.

use Respect\Validation\ValidatorBuilder as v;

We import the validator builder under the short name v. The package also registers a global v class alias, so the use statement can be omitted, but the explicit import is clearer.

if (v::alnum()->isValid($name)) {

The alnum is a validation rule that allows alphanumeric values: letters and digits. The isValid method runs the rule and returns a boolean value indicating success or failure. The second value contains a space, which is not alphanumeric, so the validation fails.

$ php simple.php
Validation passed
Validation failed

Adding a character

We can add additional allowed characters to a rule.

add_character.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$name = 'Vane-Tempest-Stewart';

echo $name, ': ', v::alnum()->isValid($name) ? 'valid' : 'invalid', "\n";
echo $name, ': ', v::alnum('-')->isValid($name) ? 'valid' : 'invalid', "\n";

$name = 'Mary Anne Vane-Tempest';

echo $name, ': ', v::alnum('-', ' ')->isValid($name) ? 'valid' : 'invalid', "\n";

In the example, we add a dash and a space to the alnum rule.

$name = 'Vane-Tempest-Stewart';

Some names contain dash characters, and some contain spaces.

echo $name, ': ', v::alnum('-')->isValid($name) ? 'valid' : 'invalid', "\n";

We pass a dash character to the alnum rule; it is accepted in addition to letters and digits. The rule takes any number of such characters, so alnum('-', ' ') allows dashes and spaces.

$ php add_character.php
Vane-Tempest-Stewart: invalid
Vane-Tempest-Stewart: valid
Mary Anne Vane-Tempest: valid

Respect Validation chaining rules

The rules can be chained. All of them must pass.

chaining.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$validator = v::alnum()->length(v::greaterThanOrEqual(4));

foreach (['John', 'Jo', 'J-hn'] as $name) {
    echo str_pad($name, 6), $validator->isValid($name) ? 'valid' : 'invalid', "\n";
}

In the example, we have two rules: alnum and length. The length rule does not take numbers; it takes another validator that is applied to the length of the value. Here it is greaterThanOrEqual(4).

The name must contain only alphanumeric characters and must have at least four characters. The word Jo is too short and J-hn contains a dash.

$ php chaining.php
John  valid
Jo    invalid
J-hn  invalid

Respect Validation combining rules

The combining of rules is similar to the chaining technique. The Validators\AllOf is used to combine multiple rules. The validators are classes in the Respect\Validation\Validators namespace, and we can create them with new.

combine_rules.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\Validators;

$nameValidator = new Validators\AllOf(
    new Validators\Alnum(),
    new Validators\Length(new Validators\Between(5, 40)),
);

foreach (['John', 'Johnny'] as $name) {
    echo str_pad($name, 8), $nameValidator->evaluate($name)->hasPassed ? 'valid' : 'invalid', "\n";
}

The example combines two validation rules with Validators\AllOf. The Length validator receives a Between validator. We call the evaluate method, which returns a Result object; its hasPassed property tells whether the validation succeeded. The word John has four characters, so it is too short; Johnny is accepted.

$ php combine_rules.php
John    invalid
Johnny  valid

Respect Validation validate method

The validate method returns a ResultQuery. It does not throw an exception; instead, we can ask it whether the validation failed and what the messages are.

validate_result.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$validator = v::alnum()->length(v::greaterThanOrEqual(4));

$result = $validator->validate('J-');

var_dump($result->hasFailed());
echo $result->getMessage(), "\n";
print_r($result->getMessages());

The hasFailed method returns true when the validation failed. The getMessage method returns the first failure message and getMessages an array of all messages. The keys are the ids of the rules; the special __root__ key describes the whole chain. Note that the result object itself is always truthy, so it cannot be used directly in an if condition.

$ php validate_result.php
bool(true)
"J-" must consist only of letters (a-z) and digits (0-9)
Array
(
    [__root__] => "J-" must pass all the rules
    [alnum] => "J-" must consist only of letters (a-z) and digits (0-9)
    [lengthGreaterThanOrEqual] => The length of "J-" must be greater than or equal to 4
)

Respect validation assert function

The assert method throws a ValidationException when the validation fails. The exception contains a complete validation report.

assert_fun.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

$name = '';

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

try {
    $validator->assert($name);
} catch (ValidationException $ex) {
    echo "Message:\n", $ex->getMessage(), "\n\n";
    echo "Full message:\n", $ex->getFullMessage(), "\n\n";
    echo "Messages:\n";

    foreach ($ex->getMessages() as $id => $message) {
        echo "$id: $message\n";
    }
}

The example uses the assert method on a validation rule and shows the error messages in three forms.

$validator->assert($name);

We validate a name value with assert. The value is an empty string, so it fails both rules.

echo "Full message:\n", $ex->getFullMessage(), "\n\n";

The getMessage method returns only the first message, getFullMessage returns a tree of all messages as an indented list, and getMessages returns an array of messages keyed by the rule id, which is the most useful form for displaying errors in a form.

$ php assert_fun.php
Message:
"" must consist only of letters (a-z) and digits (0-9)

Full message:
- "" must pass all the rules
  - "" must consist only of letters (a-z) and digits (0-9)
  - "" must not be blank

Messages:
__root__: "" must pass all the rules
alnum: "" must consist only of letters (a-z) and digits (0-9)
notBlank: "" must not be blank

Respect Validation check method

The check method stops at the first failed rule and throws the exception with the message of that rule. It is useful for guard clauses.

check_fun.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

try {
    v::alnum()->notBlank()->check('');
} catch (ValidationException $ex) {
    echo $ex->getMessage(), "\n";
}

try {
    v::intVal()->positive()->check(-5);
} catch (ValidationException $ex) {
    echo $ex->getMessage(), "\n";
}

Both examples throw the exception from the first failing rule: the empty string is not alphanumeric, and the number -5 is not positive.

$ php check_fun.php
"" must consist only of letters (a-z) and digits (0-9)
-5 must be a positive number

Respect Validation between rule

The between rule validates ranges including integers, characters, and dates.

between_rule.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$age = 34;

if (v::intVal()->between(18, 99)->isValid($age)) {
    echo "Age validation passed\n";
} else {
    echo "Age validation failed\n";
}

$char = 'g';

if (v::stringType()->between('a', 'c')->isValid($char)) {
    echo "Letter validation passed\n";
} else {
    echo "Letter validation failed\n";
}

$myDate = '2013-01-01';

if (v::dateTime('Y-m-d')->between('2009-01-01', '2019-01-01')->isValid($myDate)) {
    echo "Date validation passed\n";
} else {
    echo "Date validation failed\n";
}

The example uses the between rule.

if (v::intVal()->between(18, 99)->isValid($age)) {

This rule checks if the $age variable is between 18 and 99.

if (v::stringType()->between('a', 'c')->isValid($char)) {

This rule checks if the $char variable is between 'a' and 'c' characters. The letter g is not, so the validation fails.

if (v::dateTime('Y-m-d')->between('2009-01-01', '2019-01-01')->isValid($myDate)) {

The dateTime rule checks that the value is a date in the given format; the between rule compares it with the two specified dates.

$ php between_rule.php
Age validation passed
Letter validation failed
Date validation passed

Respect Validation objects

Object properties are validated with property. The validator reads the value of a property even if it is private.

user.php
<?php

declare(strict_types=1);

class User
{
    public function __construct(
        private string $name,
        private string $email,
    ) {
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getEmail(): string
    {
        return $this->email;
    }
}

This is user.php; it uses constructor property promotion.

validate_object.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/user.php';

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

$user = new User('Jo', 'johndoe#gmail.com');

$userValidator = v::property('name', v::alnum()->length(v::greaterThanOrEqual(4)))
    ->property('email', v::email());

try {
    $userValidator->assert($user);
} catch (ValidationException $ex) {
    echo $ex->getFullMessage(), "\n";
}

The example validates the properties of the User class.

$userValidator = v::property('name', v::alnum()->length(v::greaterThanOrEqual(4)))
    ->property('email', v::email());

These are rules for the properties of the user object. The getFullMessage output names the failed properties with a path such as .name. The Jo name is too short; the e-mail address has a hash character instead of the at sign.

$ php validate_object.php
- `User { -$name="Jo" -$email="johndoe#gmail.com" }` must pass all the rules
  - `.name` must pass the rules
    - The length of `.name` must be greater than or equal to 4
  - `.email` must be an email address

Respect Validation arrays

Request data and decoded JSON are arrays. The key rule validates an item of an array, keyOptional validates it only if it is present.

validate_array.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

$input = ['name' => 'Jo', 'email' => 'johndoe#gmail.com', 'age' => 17];

$validator = v::key('name', v::alnum()->length(v::greaterThanOrEqual(4)))
    ->key('email', v::email())
    ->key('age', v::intVal()->between(18, 99));

try {
    $validator->assert($input);
} catch (ValidationException $ex) {
    foreach ($ex->getMessages() as $field => $message) {
        echo "$field: $message\n";
    }
}

echo "---\n";

try {
    v::key('name', v::alnum())->assert(['email' => 'john@example.com']);
} catch (ValidationException $ex) {
    echo $ex->getMessage(), "\n";
}

$validator = v::keyOptional('age', v::intVal()->between(18, 99));

var_dump($validator->isValid([]));
var_dump($validator->isValid(['age' => 12]));

We validate three fields of an input array. The messages from getMessages are keyed by the field name, so we can display each message next to its form field. When a required key is missing, the message says that the key must be present. The optional key passes when it is absent, but a present value must still be valid.

$ php validate_array.php
__root__: `["name": "Jo", "email": "johndoe#gmail.com", "age": 17]` must pass all the rules
name: The length of `.name` must be greater than or equal to 4
email: `.email` must be an email address
age: `.age` must be between 18 and 99
---
`.name` must be present
bool(true)
bool(false)

Respect Validation custom message

We can provide custom validation messages. The named rule gives the value a name, which replaces the value in the root message. The second argument of assert is a template: a string for the whole validation or an array that maps rule ids to messages.

custom_message.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

$name = '';

$validator = v::named('Name', v::alnum()->notBlank());

try {
    $validator->assert($name);
} catch (ValidationException $ex) {
    print_r($ex->getMessages());
}

try {
    $validator->assert($name, [
        'alnum' => 'The name must contain only letters and digits',
        'notBlank' => 'The name must not be empty',
    ]);
} catch (ValidationException $ex) {
    print_r($ex->getMessages());
}

try {
    v::alnum()->assert('a b', 'The name must contain only letters and digits');
} catch (ValidationException $ex) {
    echo $ex->getMessage(), "\n";
}

The first block shows the messages of the named validator; the root message begins with Name. In the second block, we replace the messages of the alnum and notBlank rules with our own text. In the third block, a single string replaces the message of the failed rule.

$ php custom_message.php
Array
(
    [__root__] => Name must pass all the rules
    [alnum] => "" must consist only of letters (a-z) and digits (0-9)
    [notBlank] => "" must not be blank
)
Array
(
    [__root__] => Name must pass all the rules
    [alnum] => The name must contain only letters and digits
    [notBlank] => The name must not be empty
)
The name must contain only letters and digits

Respect Validation collections and alternatives

The each rule applies a validator to every item of a collection. The anyOf rule passes when at least one of its rules passes, the nullOr rule allows a null value, and not negates a rule.

collections.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

var_dump(v::each(v::intVal())->isValid([1, 2, 3]));

try {
    v::each(v::intVal())->assert([1, 'a', 3, 'b']);
} catch (ValidationException $ex) {
    echo $ex->getFullMessage(), "\n";
}

echo "---\n";

$status = v::anyOf(v::equals('active'), v::equals('disabled'));
var_dump($status->isValid('active'));
var_dump($status->isValid('deleted'));

$optionalEmail = v::nullOr(v::email());
var_dump($optionalEmail->isValid(null));
var_dump($optionalEmail->isValid('john@example.com'));
var_dump($optionalEmail->isValid('john'));

var_dump(v::not(v::contains('admin'))->isValid('john'));

The first check passes because all items are integers. In the second one, items at positions 1 and 3 are not; the full message names them. The anyOf validator is a kind of enumeration of the allowed values. The nullOr validator is handy for optional fields: a missing value is fine, but when it is present, it must be a valid e-mail. The last check passes because john does not contain the word admin.

$ php collections.php
bool(true)
- Each item in `[1, "a", 3, "b"]` must be valid
  - `.1` must be an integer
  - `.3` must be an integer
---
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

Respect Validation common rules

Respect Validation has rules for many common formats: e-mail addresses, URLs, IP addresses, dates, JSON strings, numbers, and others.

common_rules.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\ValidatorBuilder as v;

$checks = [
    'email' => [v::email(), 'john@example.com'],
    'invalid email' => [v::email(), 'john@'],
    'url' => [v::url(), 'https://zetcode.com/php/'],
    'ip' => [v::ip(), '192.168.0.1'],
    'date' => [v::date('Y-m-d'), '2026-02-30'],
    'digit' => [v::digit(), '12345'],
    'numeric' => [v::numericVal(), '12.5'],
    'regex' => [v::regex('/^\d{3} \d{2}$/'), '811 01'],
    'in' => [v::in(['small', 'medium', 'large']), 'medium'],
    'positive' => [v::positive(), -5],
    'json' => [v::json(), '{"name": "John"}'],
];

foreach ($checks as $label => [$validator, $value]) {
    printf("%-14s %s\n", $label, $validator->isValid($value) ? 'valid' : 'invalid');
}

The example runs several of them over sample values. The date 2026-02-30 does not exist, so the date rule rejects it. The regex rule checks the value against a regular expression, the in rule against a list of allowed values.

$ php common_rules.php
email          valid
invalid email  invalid
url            valid
ip             valid
date           invalid
digit          valid
numeric        valid
regex          valid
in             valid
positive       invalid
json           valid

Respect Validation custom rules

When no built-in rule fits, we can use the satisfies rule with any callable. The callable receives the value and returns a boolean.

satisfies.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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

$isEven = static fn(int $n): bool => $n % 2 === 0;

var_dump(v::intVal()->satisfies($isEven)->isValid(10));
var_dump(v::intVal()->satisfies($isEven)->isValid(7));

$validator = v::stringType()->satisfies(static fn(string $s): bool => $s === strrev($s));

var_dump($validator->isValid('level'));

try {
    $validator->assert('zetcode');
} catch (ValidationException $ex) {
    echo $ex->getMessage(), "\n";
}

The first rule checks that an integer is even, the second one that a string is a palindrome. The message of satisfies is generic. To create a reusable rule with its own messages, we implement the Respect\Validation\Validator interface; see the documentation.

$ php satisfies.php
bool(true)
bool(false)
bool(true)
"zetcode" must be valid

Respect Validation attributes

The validators can be used as PHP attributes. The attributes rule then validates an object according to the attributes of its properties, so the validation rules stay next to the data.

attributes.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\ValidatorBuilder as v;
use Respect\Validation\Validators\Alnum;
use Respect\Validation\Validators\Between;
use Respect\Validation\Validators\Email;
use Respect\Validation\Validators\GreaterThanOrEqual;
use Respect\Validation\Validators\Length;
use Respect\Validation\Validators\IntType;

class Registration
{
    public function __construct(
        #[Alnum, Length(new GreaterThanOrEqual(4))]
        public string $name,
        #[Email]
        public string $email,
        #[IntType, Between(18, 99)]
        public int $age,
    ) {
    }
}

$validator = v::attributes();

$valid = new Registration('John', 'john@example.com', 34);
var_dump($validator->isValid($valid));

try {
    $validator->assert(new Registration('Jo', 'john@', 12));
} catch (ValidationException $ex) {
    echo $ex->getFullMessage(), "\n";
}

We put validators in attributes of the promoted constructor properties of the Registration class. The v::attributes() rule reads these attributes with reflection and validates the object. The first object is valid. The second one has a short name, an invalid e-mail address and an age below 18, and the full message lists the properties that failed.

$ php attributes.php
bool(true)
- `Registration { +$name="Jo" +$email="john@" +$age=12 }` must pass all the rules
  - `.name` must pass the rules
    - The length of `.name` must be greater than or equal to 4
  - `.email` must be an email address
  - `.age` must pass the rules
    - `.age` must be between 18 and 99

Source

The Respect Validation - GitHub repository

Respect Validation documentation

In this article we have used the PHP Respect Validation library to validate values, arrays and objects. We have chained rules, read the error messages, customized them, and used validators as attributes. See also the PHP exceptions and PHP GET/POST request tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.