Create Reusable Custom Validation Rules in Laravel
Laravel allows you to create custom validation rules when built-in validation isn't enough. Instead of repeating complex validation logic across multiple Form Requests, you can encapsulate it into a reusable rule class.
Create a Rule
Generate a new validation rule using Artisan:
php artisan make:rule UsernameRule
Laravel creates a new rule class inside:
app/Rules/UsernameRule.php
Define the Validation Logic
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class UsernameRule implements ValidationRule
{
public function validate(string $attribute,
mixed $value,
Closure $fail): void {
if (in_array(strtolower($value), [
'admin',
'root',
'support',
])) {
$fail('This username is reserved.');
}
}
}
Use the Rule
use App\Rules\UsernameRule;
public function rules(): array
{
return [
'username' => [
'required',
new UsernameRule(),
],
];
}
That's it! The rule can now be reused anywhere in your application.
Why Use Custom Validation?
Custom validation rules help you:
- Reuse validation logic
- Keep Form Requests concise
- Centralize business rules
- Improve code readability
- Simplify testing
When Should You Create a Custom Rule?
Create one when:
- Validation is used in multiple places
- Business rules are more complex than built-in validators
- You want cleaner and more maintainable code