I need to setup a validation rule for two date fields arrivalFrom and arrivalTo. The fields are optional, but if one of the fields are present the other is required, and should follow a specific format.
// Validation.
$validator = Validator::make($request->all(), [
'amount' => 'required|numeric',
'arrivalFrom' => 'required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
'arrivalTo' => 'required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
]);
The validation works if the only rule set is "required_with" but as soon as date_format or before is set, the required_with is ignored.
Validation Message
Please not that neither of the fields "arrivalFrom" / "arrivalTo" are set.
The arrival from does not match the format dd/mm/yy.
The arrival from must be a date before arrival to.
The arrival to does not match the format dd/mm/yy.
The arrival to must be a date before arrival to.
Is there a way to achieve these validation in one go, instead of checking if the input is present and then set validation rules.
I'm using Laravel 5.4.
EDIT : Solution
// Validation.
$validator = Validator::make($request->all(), [
'amount' => 'required|numeric',
'arrivalFrom' => 'required_with:arrivalTo|nullable|date_format:d/m/y|before:arrivalTo',
'arrivalTo' => 'required_with:arrivalFrom|nullable|date_format:d/m/y|after:arrivalFrom',
]);