Lorenz
Lorenz

Reputation: 43

How to ignore a validation rule if a field is null?

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

Upvotes: 0

Views: 4311

Answers (2)

matticustard
matticustard

Reputation: 5149

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',
    ]);
}

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219938

Use the nullable rule:

'retired_on' => 'nullable|date_format:Y/m/d|after_or_equal:entered_on',

Upvotes: 2

Related Questions