Site Admin
Site Admin Founder of MeaningArticles
1152 Views

Validate custom Date Format using Laravel validator

Hello Dev.

On this Laravel php Article, i'm able to permit you to understand a way to validate date with specified date format the use of Laravel validation rules.

Laravel constantly introduce some incredible functions with its updates and date validation is certainly one of them.

you can validate date after, date_format, after_or_equal:date, before:date, before_or_equal:date and many others.

Laravel date validation rules support all format supported by means of php's Date class.

In this example, you'll see the usage 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

So let's start the lesson...


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 situation, there should be validation like end date have to 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 assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.

Happy Coding.....