What is Respect\\Validation?
Respect\\Validation is a powerful and expressive data validation library for PHP. It allows you to build complex validation rules using method chaining, making the code clean and readable. The library supports over 60 built-in rules (from email validation to CPF/CNPJ validation) and is easily extendable with custom rules.
Why is validation needed?
Data validation is a critical stage in processing user input, API requests, or data from external sources. Without it, the application is vulnerable to:
- SQL injections and XSS attacks
- Incorrect data causing errors
- Violation of business logic
Respect\\Validation solves these problems by providing a unified interface for filtering and checking.
Installation
Install the library via Composer:
composer require respect/validationAfter installation, include the autoloader and use the namespace:
require 'vendor/autoload.php';use Respect\\Validation\\Validator as v;Main Features
The library offers:
- Rule chaining:
v::alnum()->noWhitespace()->length(5, 20)->validate($input) - Custom error messages:
v::email()->setName('Email')->assert($input) - Group validation:
v::attribute('name', v::stringType())->attribute('age', v::intVal()) - Optional fields and conditional rules (e.g., validation only if the field is present).
PHP Code Example
Simple registration form validation:
<?phprequire 'vendor/autoload.php';use Respect\\Validation\\Validator as v;
$data = [ 'username' => 'john_doe', 'email' => 'john@example.com', 'password' => 'secret123', 'age' => 25];
$usernameValidator = v::alnum()->noWhitespace()->length(4, 20);$emailValidator = v::email();$passwordValidator = v::length(8, 64);$ageValidator = v::intVal()->between(18, 120);
try { $usernameValidator->setName('Username')->assert($data['username']); $emailValidator->setName('Email')->assert($data['email']); $passwordValidator->setName('Password')->assert($data['password']); $ageValidator->setName('Age')->assert($data['age']); echo 'All data is valid!';} catch (\\Respect\\Validation\\Exceptions\\NestedValidationException $e) { echo implode('<br>', $e->getMessages());}Result on error: "Username must contain only letters and digits" etc.
When to Use
- Website forms — registration, feedback, ordering
- REST API — validating JSON requests before processing
- Data import — validating CSV/Excel before writing to the database
- Command-line scripts — checking CLI arguments
Respect\\Validation is suitable for projects of any size — from simple websites to frameworks (Laravel, Symfony). It replaces cumbersome if-else constructs and simplifies testing.