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

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
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
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 →
FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches image

FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches

Read article
Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot image

Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot

Read article
Nimbus: An In-Browser API Testing Playground for Laravel image

Nimbus: An In-Browser API Testing Playground for Laravel

Read article
Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout image

Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout

Read article
Handling Large Datasets with Pagination and Cursors in Laravel MongoDB image

Handling Large Datasets with Pagination and Cursors in Laravel MongoDB

Read article
Driver-Based Architecture in Spatie's Laravel PDF v2 image

Driver-Based Architecture in Spatie's Laravel PDF v2

Read article