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

laravelcloud logo
Laravel Cloud

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

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article