Get expert guidance in a few days with a Laravel code review

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
Laravel Cloud

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

Visit Laravel Cloud
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

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

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

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

Shift
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
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
The Inertia v3 Beta is Here image

The Inertia v3 Beta is Here

Read article
Polyscope Is an Ai-First Dev Environment for Orchestrating Agents image

Polyscope Is an Ai-First Dev Environment for Orchestrating Agents

Read article
Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements image

Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements

Read article
Ward: A Security Scanner for Laravel image

Ward: A Security Scanner for Laravel

Read article
Kit: An Opinionated API Starter Kit for Laravel image

Kit: An Opinionated API Starter Kit for Laravel

Read article
Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support image

Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support

Read article