Laravel: How do I validate a date ONLY if the date exists?

Viewed 3958

I have a form, it has a date field called starts, which is optional:

...
<input type="date" name="starts">
...

Then I created a Request in Laravel that checks, among other things, if starts is a date, so the rules() function in the Request is somthing like:

public function rules()
{
  return [
    ... (more validation rules)
    'starts'             => 'date',
    ... (more validation rules)
  ];
}

So, when I submit the form and there's no starts, the validation rules kicks in, it says it's not a date, and returns to my form.

How do I tell Laravel that starts is a date, only if it is present?

I'm looking something like the validation in files, which only take place if there's a file present

2 Answers

You can add "nullable" for your laravel validation rule like so:

'starts' => 'date|nullable'

Try 'starts' => 'nullable|date' as validation rule. There is a section about this in the documentation.

Related