49

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?

2
  • You could try with just the date rule, if not I would suggest to change it to Y-m-d before validating it. laravel.com/docs/5.6/validation#rule-date Commented May 11, 2018 at 8:20
  • If you're using input[type="date"] with your datepicker, the value passed will always be Y-m-d. Commented May 11, 2018 at 8:21

2 Answers 2

118

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';
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.