How to validate custom Date Format with Laravel validator

In this Laravel PHP Tutorial, We will learn how to validate custom date format with laravel validator.

Laravel has provided many features and with its updates for data validation. You can validate the incoming request the way you want using middleware and if also using some inbuilt function. In today’s tutorial, we will learn how to validate only the date format.

You can validate date after, date_format, after_or_equal:date, before:date, before_or_equal:date etc. Laravel date validation rules support all formats supported by PHP’s Date class.

In this example, you will see the use of the following different date validation rules that are provided by Laravel. Some of them I have mentioned below, You will see examples for each which will help you to understand the use of date validation easily in laravel.

  • date
  • date_format
  • after:date
  • after_or_equal:date
  • before:date
  • before_or_equal:date

Date Validation

This is the simple validation and you can validate the incoming request value by simply putting the input. value in the array with a date.

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

Date Validation for date_format

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

Date Validation for after

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

Date Validation for after_or_equal

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

Date Validation for before

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'
    ]);
  
}

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'
    ]);
  
}

Sometimes we develop an application having start and end date functionality for any reservation and in this case, there should be validation like the end date must be after the start date. This is a very useful and easy-to-use validation that can be easily used in travel or hotel kinds of websites.

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

Recommended Posts For You

Spread the love