Polyscope - The agent-first dev environment for Laravel

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Debounceable Queued Jobs in Laravel 13.6.0 image

Debounceable Queued Jobs in Laravel 13.6.0

Read article
Build Custom Middleware for Query Performance Monitoring and Optimization in Laravel with MongoDB image

Build Custom Middleware for Query Performance Monitoring and Optimization in Laravel with MongoDB

Read article
Laravel API Starter Kits Are Coming Soon! image

Laravel API Starter Kits Are Coming Soon!

Read article
An Opinionated Agent Skill for Building REST APIs in Laravel image

An Opinionated Agent Skill for Building REST APIs in Laravel

Read article
Launch Your Dream SaaS Application with SaaSykit image

Launch Your Dream SaaS Application with SaaSykit

Read article
Spatie Shares Their Coding Guidelines as AI Skills image

Spatie Shares Their Coding Guidelines as AI Skills

Read article