cakephp/validation
Lightweight validation library from the CakePHP ecosystem. Define rules and validators for arrays and data objects, run checks, and collect readable error messages. Useful standalone or within CakePHP apps for consistent input validation.
Installation Add the package via Composer:
composer require cakephp/validation
Basic Usage Import the validator and define rules in a Laravel service or controller:
use Cake\Validation\Validator;
$validator = new Validator();
$validator->add('email', 'custom', [
'rule' => 'email',
'message' => 'Invalid email format'
]);
First Use Case: Form Validation Validate user input in a Laravel request handler:
$data = ['email' => 'test@example.com'];
$errors = $validator->validate($data);
if (!empty($errors)) {
// Handle validation errors (e.g., return JSON response)
}
Key Files to Explore
src/Validator.php (Core validation logic)src/Validation.php (Validation rules and helpers)tests/ (Test cases for edge cases and rules)Define reusable validation rules in a dedicated class:
class UserValidator extends Validator {
public function __construct() {
$this->add('username', 'notEmpty', [
'rule' => 'notEmpty',
'message' => 'Username cannot be empty'
]);
$this->add('password', 'length', [
'rule' => ['minLength', 8],
'message' => 'Password must be at least 8 characters'
]);
}
}
Use in Laravel's FormRequest or manually in controllers:
public function validateCustom(Request $request) {
$validator = new UserValidator();
$data = $request->all();
$errors = $validator->validate($data);
if ($errors) {
return response()->json($errors, 422);
}
// Proceed with logic
}
Extend the validator with custom rules:
$validator->add('custom_field', 'customRule', [
'rule' => function ($value) {
return str_contains($value, 'admin');
},
'message' => 'Field contains restricted text'
]);
Validate multiple datasets (e.g., bulk imports):
$validator = new Validator();
$validator->add('name', 'notEmpty');
$validator->add('age', 'range', ['min' => 18]);
$users = [
['name' => 'John', 'age' => 25],
['name' => '', 'age' => 17]
];
$results = array_map(function ($user) use ($validator) {
return $validator->validate($user);
}, $users);
Bind the validator to Laravel's container for dependency injection:
// In AppServiceProvider
$this->app->bind(Validator::class, function () {
return new Validator();
});
No Laravel-Specific Features
Validator facade, FormRequest hooks). Manual error handling is required.trans() helper manually).Rule Naming Conflicts
email, date) may conflict with Laravel's built-in rules. Prefix custom rules (e.g., cake_email).Strict Typing
$data = array_map('strval', $request->all()); // Ensure strings
No Automatic Sanitization
filter_var() or similar for security.Enable Debug Mode
Set debug to true in the validator for detailed error messages:
$validator = new Validator(['debug' => true]);
Inspect Rules Dump the validator's rules to debug:
dd($validator->getRules());
Test Edge Cases
Validate with null, empty strings, and malformed data to catch rule issues early.
Custom Validators
Extend Cake\Validation\Validator to add domain-specific rules:
class MyCustomValidator extends Validator {
public function __construct() {
$this->add('ssn', 'ssnFormat', [
'rule' => function ($value) {
return preg_match('/^\d{3}-\d{2}-\d{4}$/', $value);
}
]);
}
}
Plugin Integration Use the package alongside Laravel's validator for hybrid validation:
$cakeValidator = new Validator();
$laravelValidator = Validator::make($data, [
'email' => 'required|email',
]);
$errors = $cakeValidator->validate($data);
if ($errors) {
$laravelValidator->errors()->merge($errors);
}
Performance Optimization Reuse validator instances for repeated validations (e.g., in loops):
$validator = new Validator();
foreach ($items as $item) {
$validator->validate($item); // Reuse instance
}
Configuration Override default settings via constructor:
$validator = new Validator([
'allowEmpty' => false, // Disallow empty values
'preserveData' => true // Keep original data on failure
]);
How can I help you explore Laravel packages today?