Laravel validate different types of Date Format with Laravel validator

Laravel validate different types of Date Format with Laravel validator

Laravel provides different types of validators. But in this article i will let you know how to validate different types of Date Format with laravel validator.

Laravel provides different type of date validations like date after, date_format, after_or_equal:date, before:date, before_or_equal:date etc and these validation rules support all the date format supported by PHP’s Date class.

In this example, we will demostrate the use of following date validation rules:

  1. date
  2. date_format
  3. after:date
  4. after_or_equal:date
  5. before:date
  6. before_or_equal:date

In all our example we will use these rules inside a save method. You are free to use anywhere in your controller’s metthod.

1.  Simple Date Validation

public function save(Request $request)
{
   
    $request->validate([        
        'date_of_birth' => 'date'
    ]);
  
}

2. Date Validation for Specific Date Format

public function save(Request $request)
{
   
    $request->validate([        
        'date_of_birth' => 'date_format:m/d/Y'
    ]);
  
}

3. Date Validation for After some days

public function save(Request $request)
{
   
    $request->validate([        
        'start_date' => 'date_format:m/d/Y|after:tomorrow'
    ]);
  
}

4. Date Validation for After or Equal a Specific Date

public function save(Request $request)
{
   $now=date('m/d/Y');
    $request->validate([        
        'start_date' => 'date_format:m/d/Y|after_or_equal:'.$now
    ]);
  
}

5. Date Validation for Before a Specific Date

public function save(Request $request)
{
   
    $request->validate([        
        'end_date' => 'date_format:m/d/Y|before:start_date',
        'start_date' => 'date_format:m/d/Y|after:tomorrow'
    ]);
  
}

6. Date Validation for Before or Equal

public function save(Request $request)
{
   
    $request->validate([        
        'end_date' => 'date_format:m/d/Y|before_or_equal:start_date',
        'start_date' => 'date_format:m/d/Y|after:tomorrow'
    ]);
  
}

Above are the uses of  six date validation rules provided by Laravel.

Suppose there is a case where there are two dates start date and end date and you need to validate end date that should be greater than start date then how would you implement in laravel using one of the above rule. Let’s take a look of that type of implementation.

public function save(Request $request)
{
   
    $request->validate([       
        'start_date' => 'date_format:m/d/Y',
        'end_date' => 'date_format:m/d/Y|after:start_date'
    ]);
   
}