jacobdo
jacobdo

Reputation: 1615

Validating a custom date format in with laravel validator

In my app, the user selects date from a datepicker and the date is then displayed in the input in a format that corresponds user's locale.

When the form is submitted, I would like to validate the respective date, however, the validator does not know the date format that the date was submitted in.

My question is whether I should mutate the date into Y-m-d before it is passed to validator or is there a way I can tell the Validator the right format to validate in?

Upvotes: 47

Views: 108358

Answers (2)

Niraj Shah
Niraj Shah

Reputation: 15457

The easier option is to use the Laravel date_format:format rule (https://laravel.com/docs/5.5/validation#rule-date-format). It's a built-in function in Laravel without the need for a custom rule (available in Laravel 5.0+).

You can do:

$rule['date'] = 'required|date_format:d/m/Y';

or

$rule['date'] = 'required|date_format:Y-m-d';

Upvotes: 117

Saurabh
Saurabh

Reputation: 2775

Laravel Custom Validation Rules

You can define the multi-format date validation in your AppServiceProvider

class AppServiceProvider extends ServiceProvider  
{
  public function boot()
  {
    Validator::extend('new-format', function($attribute, $value, $formats) {

      foreach($formats as $format) {

        $parsed = date_parse_from_format($format, $value);

        // validation success
        if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
          return true;
        }
      }

      // validation failed
      return false;
    });
  }
}

Now you can use custom validation rule:

'your-date' => 'new-format:"Y-m-d H:i:s.u","Y-m-d"'

Upvotes: 7

Related Questions