How to validate an array of datetimes in laravel?

by hal.littel , in category: PHP Frameworks , 6 months ago

How to validate an array of datetimes in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@hal.littel 

In Laravel, you can validate an array of datetimes using the array validation rule along with the date_format rule. Here's an example of how you can validate an array of datetimes in Laravel:

1
2
3
4
$validatedData = $request->validate([
    'datetimes' => 'required|array',
    'datetimes.*' => 'required|date_format:Y-m-d H:i:s',
]);


In this example, we are validating the datetimes array in the request using the array rule to ensure that it is an array. We are then using the datetimes.* syntax to validate each element of the array individually. The date_format:Y-m-d H:i:s rule is used to validate each datetime value in the array to ensure it is in the correct format (e.g., 2022-01-01 12:00:00).


If the validation fails, Laravel will automatically redirect the user back to the form with the validation errors. You can then display the error messages in your view using the withErrors method.