Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Validation: Custom Rules

Create custom validation rules for complex requirements.

16 January 20261 min readLaravelاقرأ بالعربية

On this page

  1. Create Rule
  2. Rule Class
  3. Use Rule
  4. Closure Rule

Custom validation rules:

Create Rule

php artisan make:rule Uppercase

Rule Class

class Uppercase implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper($value) !== $value) {
            $fail('The :attribute must be uppercase.');
        }
    }
}

Use Rule

php
$request->validate([
    'name' => ['required', new Uppercase],
]);

Closure Rule

'email' => [
    function ($attribute, $value, $fail) {
        if (!str_ends_with($value, '@company.com')) {
            $fail('Must be a company email.');
        }
    },
],
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read