Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
jacobdo Avatar asked May 11 '18 08:05

jacobdo


People also ask

How do you validate a date field?

The date in the date field has to be after today's date and not in the past. It also has to be within 30 days from today's date. So if today is 15/01/2013, then the form can only accept any date within 30 days after the 15/02/2013, so the 14/04/2007 plus 30 days!

How do I validate a timestamp in Laravel?

Just create a new validation rule in laravel to validate the timestamp... Validator::extend('isTimeStamp', function($attribute, $value, $parameters) { return ((string) (int) $value === $value) && ($value <= PHP_INT_MAX) && ($value >= ~PHP_INT_MAX); }); You can now use isTimeStamp validation rule to validate timestamp.


Video Answer


2 Answers

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';
like image 116
Niraj Shah Avatar answered Oct 18 '22 19:10

Niraj Shah


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"'

like image 40
Saurabh Avatar answered Oct 18 '22 18:10

Saurabh