0
votes

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

2 Answers

2
votes

I fixed the issue myself, I added the rule nullable which worked as a charm. So if the field is not null, the other validation rules overrule.

// 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',
]);
0
votes
// Validation.
$validator = Validator::make($request->all(), [
    'amount'      => 'required|numeric',
    'arrivalFrom' => 'required_if:arrivalTo,"!="," "|required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
    'arrivalTo'   => 'required_if:arrivalFrom,"!="," "|required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
]);

I am not sure about this. As I have never used required_if and required_with together but you can give it a try? Not sure if it will solve your problem or not.Let me know if it does.