Duy Trần
Duy Trần

Reputation: 204

How to validate date time with many format in laravel

I want to check my request datetime with many format look like below format:

Y-m-d
Y-m-
Y-m

In Laravel, I use Validator to validate datetime, but Validator can not make checking with many format. This is my code:

Validator::make(['date' => $departureDate], [
   'date' => 'required|date_format:Y-m-d, Y-m, Y-m-'
]);

How can I do it in laravel Please help me! Many thanks!

Upvotes: 3

Views: 4939

Answers (2)

Salar Bahador
Salar Bahador

Reputation: 1494

You must write a custom validation format for that. Laravel's date_format expects only one parameter and not capable of handling multi-formats. There are Two ways to add custom validation. first, one is making a rule repository and add your validation logic there. Here Taylor Otwell explained this method.

The other way to doing that is extend validation in app service provider and add new rule there. add this code in app service provider:

use Illuminate\Support\Facades\Validator;


Validator::extend('multi_date_format', function ($attribute, $value, $parameters,$validator) {

    $ok = true;

    $result = [];

      // iterate through all formats
      foreach ($parameters as $parameter){

         //validate with laravels standard date format validation
         $result[] = $validator->validateDateFormat($attribute,$value,[$parameter]);
      }

    //if none of result array is true. it sets ok to false
    if(!in_array(true,$result)){
        $ok = false;
        $validator->setCustomMessages(['multi_date_format' => 'The format must be one of Y-m-d ,Y-m or Y-m-']);
    }

    return $ok;
});

And here you can use it this way:

$validator = Validator::make(['date' => '2000-02-01'], [
    'date' => 'required|multi_date_format:Y-m-d,Y-m,Y-m-'
]);

if($validator->fails()) {
    $errors = $validator->errors()->all();
}

Upvotes: 1

Maxim Abdalov
Maxim Abdalov

Reputation: 559

You can register custom validator in file app/Providers/AppServiceProvider.php in boot method.

Validator::extend('several_date_format', function ($attribute, $value, $parameters,$validator) {
    foreach ($parameters as $parameter){
        if (!$validator->validateDateFormat($attribute,$value,[$parameter]))
           return false;
    }
    return true;
});

Now you can use it

'your_date' => 'required|several_date_format:Y-m-d,...'

Optional after it you can add custom message in resources/lang/en/validation.php

return [
   ...
   'several_date_format' => 'Error text'
   ...
]

Upvotes: 0

Related Questions