Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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 →
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article
Livewire 4 Support in Laravel VS Code Extension v1.4.3 image

Livewire 4 Support in Laravel VS Code Extension v1.4.3

Read article