Laravel Tutorials

Building Powerful Date Validation with Laravel's Date Rule

Published
Building Powerful Date Validation with Laravel's Date Rule image

Laravel introduces a fluent Date rule that transforms how you validate dates in your applications. This chainable interface simplifies complex date validation requirements into readable, maintainable code.

The basic implementation demonstrates the rule's flexibility:

use Illuminate\Validation\Rules\Date;
 
public function rules()
{
return [
'start_date' => [
'required',
new Date // Basic date validation
],
'end_date' => [
'required',
(new Date)
->after('start_date')
->before('2025-01-01')
],
'birth_date' => [
'required',
(new Date)
->format('d/m/Y')
->beforeToday()
]
];
}

Here's how this rule streamlines validation in a reservation system:

class ReservationController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'check_in' => [
'required',
(new Date)
->format('Y-m-d')
->afterOrEqual('today')
->before(now()->addMonths(6))
],
'check_out' => [
'required',
(new Date)
->format('Y-m-d')
->after('check_in')
],
'special_request_by' => [
'nullable',
(new Date)
->format('Y-m-d')
->between('today', 'check_in')
],
'guest_birthday' => [
'nullable',
(new Date)
->format('m/d/Y')
->beforeOrEqual('today')
->after(now()->subYears(120))
]
]);
 
Reservation::create($validated);
 
return redirect()->route('reservations.confirmation');
}
}

The Date rule's chainable methods create an expressive syntax that makes even complex date validation requirements easy to understand and maintain.

Harris Raftopoulos photo

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

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Validate and Convert HEIC Images in Laravel image

Validate and Convert HEIC Images in Laravel

Read article
Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues image

Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Read article
Reject Unexpected Array Keys with Laravel Validation image

Reject Unexpected Array Keys with Laravel Validation

Read article
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article