framework icon indicating copy to clipboard operation
framework copied to clipboard

[11.x] Add Customizable Date Validation Rule with Flexible Date Constraints

Open michaelnabil230 opened this issue 3 months ago • 5 comments

This pull request introduces a new, customizable Date validation rule for Laravel. The Date rule simplifies date validation by offering chainable methods that allow for complex date requirements directly within the rule definition. This enhancement includes methods to specify date formats, enforce that dates are before or after specific dates (including "today"), and to ensure dates are on or before/after specified constraints.

With this addition, developers can create readable and flexible date validation rules without having to write multiple rules separately in the validation array.

Features

  • format($format): Specifies a date format for validation. Defaults to 'Y-m-d' if not specified.
  • afterToday(): Ensures the date is after today’s date.
  • beforeToday(): Ensures the date is before today’s date.
  • after($date): Ensures the date is after the specified date.
  • afterOrEqual($date): Ensure the date is on or after the specified date.
  • before($date): Ensures the date is before the specified date.
  • beforeOrEqual($date): Ensure the date is on or before the specified date.
  • afterOrEqual($date): Ensures the date is on or after the specified date.
  • beforeOrEqual($date): Ensures the date is on or before the specified date.
  • between($from, $to): Ensure the date is between two dates.
  • betweenOrEqual($from, $to): Ensure the date is between or equal to two dates.

Example Usage

Here is an example of how to use the Date rule in a Laravel form request:

use Illuminate\Validation\Rules\Date;

public function rules()
{
    return [
        'start_date' => [
            'required',
            new Date, // Defaults to validating the date
        ],
        'end_date' => [
            'required',
            (new Date)->after('start_date')->before('2025-01-01'), // Ensures end date is after start_date and before 2025-01-01
        ],
        'birth_date' => [
            'required',
            (new Date)->format('d/m/Y')->beforeToday(), // Validates birth_date is before today in 'd/m/Y' format
        ],
    ];
}

Benefits

This Date rule class:

  • Provides a clear, readable, and flexible way to define date validation rules.
  • Reduces redundancy in validation logic.
  • Ensures maintainable and concise validation definitions in complex date requirements.

michaelnabil230 avatar Nov 10 '24 20:11 michaelnabil230