Laravel Custom Validation Rules for Enhanced Data Integrity

Last updated on by

Laravel Custom Validation Rules for Enhanced Data Integrity image

Building robust Laravel applications often requires validation logic beyond the standard rules. Custom validation rules provide a structured approach to handle complex business requirements while maintaining clean, testable code.

Creating a custom validation rule starts with the Artisan command to generate the rule class structure. This creates a dedicated validation object that implements Laravel's ValidationRule interface:

namespace App\Rules;
 
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
 
class ValidSlug implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!preg_match('/^[a-z0-9-]+$/', $value)) {
$fail('The :attribute must only contain lowercase letters, numbers, and dashes.');
}
}
}

Applying custom rules follows the same pattern as built-in validation rules. You can integrate them seamlessly into form requests or controller validation:

use App\Rules\ValidSlug;
 
$request->validate([
'slug' => ['required', new ValidSlug],
'title' => ['required', 'string', 'max:255'],
]);

Consider a blog system where you need to validate category codes. A simple alphanumeric validator ensures consistent formatting:

namespace App\Rules;
 
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
 
class CategoryCode implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (strlen($value) !== 3 || !ctype_alnum($value)) {
$fail('The :attribute must be exactly 3 alphanumeric characters.');
}
}
}
$request->validate([
'name' => ['required', 'string', 'max:100'],
'code' => ['required', new CategoryCode],
'description' => ['nullable', 'string'],
]);

When validation requires flexibility, you can pass parameters to your custom rules during instantiation:

namespace App\Rules;
 
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
 
class MinimumWordCount implements ValidationRule
{
public function __construct(private int $minimumWords)
{
}
 
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$wordCount = str_word_count(strip_tags($value));
 
if ($wordCount < $this->minimumWords) {
$fail("The :attribute must contain at least {$this->minimumWords} words.");
}
}
}
$request->validate([
'title' => ['required', 'string', 'max:200'],
'content' => ['required', new MinimumWordCount(50)],
'excerpt' => ['nullable', new MinimumWordCount(10)],
]);

When validation requires database interaction, custom rules can access Eloquent models and other services. This example ensures email uniqueness within specific organizational boundaries:

namespace App\Rules;
 
use Closure;
use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
 
class UniqueEmailInDepartment implements ValidationRule
{
public function __construct(private int $departmentId)
{
}
 
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$exists = User::where('email', $value)
->where('department_id', $this->departmentId)
->exists();
 
if ($exists) {
$fail('This email address is already registered in your department.');
}
}
}

Testing custom validation rules becomes straightforward with dedicated test classes. You can verify both passing and failing scenarios:

class ValidSlugTest extends TestCase
{
public function test_accepts_valid_slugs()
{
$rule = new ValidSlug;
$failed = false;
 
$rule->validate('slug', 'my-blog-post', function() use (&$failed) {
$failed = true;
});
 
$this->assertFalse($failed);
}
 
public function test_rejects_invalid_slugs()
{
$rule = new ValidSlug;
$failed = false;
 
$rule->validate('slug', 'My Blog Post!', function() use (&$failed) {
$failed = true;
});
 
$this->assertTrue($failed);
}
}

Custom validation rules transform specific requirements into reusable components that integrate naturally with Laravel's validation system. They promote consistency across your application while keeping validation logic organized and testable. Whether you're handling URL slugs, content requirements, or complex business rules, custom validation provides the flexibility needed for robust applications.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media

The latest

View all →
In-Memory Eloquent Models with Truffle image

In-Memory Eloquent Models with Truffle

Read article
Detect and Resolve Laravel Schema Drift with MigrAlign image

Detect and Resolve Laravel Schema Drift with MigrAlign

Read article
Laravel Cloud Adds Scale-to-Zero and Spending Limits image

Laravel Cloud Adds Scale-to-Zero and Spending Limits

Read article
Shift + AI = Fully Automated Laravel Upgrades image

Shift + AI = Fully Automated Laravel Upgrades

Read article
Laracon AU 2026 Announces Full Speaker Lineup, Schedule, and Workshops image

Laracon AU 2026 Announces Full Speaker Lineup, Schedule, and Workshops

Read article
Parsel: Parse PDFs, Office Documents, and Images in PHP image

Parsel: Parse PDFs, Office Documents, and Images in PHP

Read article