0
votes

I'm using Laravel 5.4 and I have 2 date fields. The first is required and the second is optional.

I'm having problems with the validation when the second date field is empty.

I understand why but only want to run the before_or_equal rule if the second date is not empty

$this->validate($request, [
    'start_date' => 'required|date|before_or_equal:end_date',
    'end_date' => 'nullable|bail|date|after_or_equal:start_date',
]);

How can I update my code ignore the rule if the date field is empty?

I did think about this

if($request->has('end_date')) {
    //do something
}

The only other option is to create a custom validation rule and compare the dates

2
Why aren't you using php artisan make:request FormRequest and having them on their own files?Option
I don't think so he is using FormRequest.Raza Mehdi

2 Answers

1
votes

No need to put both condition remove |before_or_equal:end_date from start_date. Only after_or_equal:start_date would work

Use required_with:foo,bar,...

Try like this

$this->validate($request, [
    'start_date' => 'required|date',
    'end_date' => 'required_with:start_date|nullable|bail|date|after_or_equal:start_date',
]);
0
votes

I would do it like this:

$rules = [
    'start_date' => 'required|date|before_or_equal:end_date',
];

if ($request->get('end_date') != '') {
    $rules['end_date'] = 'required|date|after_or_equal:start_date';
}

$this->validate($request, $rules);