Alex
Alex

Reputation: 6645

Laravel validation rule nullable if not required

On my form I want field to be required based on whether or not a checkbox is checked. If its not checked I want them to be nullable, if it is checked I want them to be validated using the rest of the rules. Here's my validation rules:

$invoices = $request->validate([
    'Checkbox' => 'required',
    'UnitAmount' => 'required_if:Checkbox,true',
    'Quantity' => 'required_if:Checkbox,true|numeric',
    'Description'   => 'required_if:Checkbox,true|string'
]);

However if the checkbox is not checked then this code is still evaluating the numeric/strong rule. I want the validation to ignore the other rules if the checkbox is checked. How can I accomplish this? Like a nullable_unless:Checkbox,true rule

Upvotes: 0

Views: 1102

Answers (1)

Sergej Tihonov
Sergej Tihonov

Reputation: 241

Your validation rules are correct and working as expected.
If Checkbox is true then other fields are validated.
If Checkbox is false (or something else) then no validation is done and I go to the next step.

Tested them in one of my Project in a form.
Tested also if this could be a type problem, but it works with both a bool and a string.

Have you checked the value of Checkbox in the request. Looks for me, that it is always true.

Upvotes: 0

Related Questions