0

I have these rules for 2 dates. But I want the before_or_equal rule to be followed only when retired_on date has been inputted. How do I do this? sometimes doesn't solve this problem. If there is no input on retired_on date, one has to be able to input entered_on without any errors. With these 2 rules, an error appears right at the beginning since retired_on default is blank.

'entered_on' => 'required|date_format:Y/m/d|before_or_equal:retired_on',
'retired_on' => 'date_format:Y/m/d|after_or_equal:entered_on',
patricus
  • 59,488
  • 15
  • 143
  • 145
Lorenz
  • 43
  • 3
  • 9
  • 1
    I'm using Laravel 5.1. The nullable rule does not exist in this version. What am I to do? I can't upgrade as this is a job not a personal project. – Lorenz Aug 09 '19 at 05:06

2 Answers2

2

Use the nullable rule:

'retired_on' => 'nullable|date_format:Y/m/d|after_or_equal:entered_on',
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

Since you say you can't use nullable or upgrade the Laravel version, you could always separate it out and validate for that field conditionally.

// your other input validations
$this->validate($request, [
    'entered_on' => 'required|date_format:Y/m/d|before_or_equal:retired_on',
]);

// only validate 'retired_on' if it exists and is not null
if ($request->has('retired_on') && !is_null($request->input('retired_on'))) {
    // pre-check passed, do validation
    $this->validate($request, [
        'retired_on' => 'date_format:Y/m/d|after_or_equal:entered_on',
    ]);
}
matticustard
  • 4,850
  • 1
  • 13
  • 18