Site Admin
Site Admin Founder of MeaningArticles
35 Views

Validate custom Date Format using Laravel validator

Hello Dev.

In this Laravel PHP Article, I will let you know how to validate date with specified date format using Laravel validation rules.

Laravel always introduce some awesome features with its updates and date validation is one of them.

You can validate date after, date_format, after_or_equal:date, before:date, before_or_equal:date etc.

Laravel date validation rules support all format supported by PHP's Date class.

In this example, you will see the use of following date validation rules that is provided by Laravel:

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


1. Date Validation

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

 

2. Date Validation for date_format

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

 


3. Date Validation for after

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

 

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

 

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

 

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

Sometime we develop an application having start and end date functionality for any reservation and in this case, there should be validation like end date must be after start date.

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

I hope it can help you, thanks for visit my articles if you like my article then share with your friend and on social platform.