Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 555
luisfer Avatar asked Mar 05 '23 17:03

luisfer


2 Answers

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

'starts' => 'date|nullable'
like image 110
kapitan Avatar answered Mar 12 '23 21:03

kapitan


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

like image 40
Streamfighter Avatar answered Mar 12 '23 21:03

Streamfighter