Laravel validation required if field not equal to
Solution 1
I would suggest you use
required_unless:currency,0
according to [1]: https://laravel.com/docs/5.5/validation#rule-required-unless
Solution 2
required_if:currency, ==, 0
works because the currency
value must be equal to any of the values that follow the value name (in this case currency
). In other words, price
is required in this case if currency is either ==
or 0
.
So the ==
doesn't mean the usual "equals" in this case. It is just taken as a string value. That is also why required_if:currency, !=, 0
does not work as you expected it to.
To make the price
field required only when the currency
field value is not equal to 0, you could use required_unless:currency,0
.
In other words, price
is always required, unless currency
is equal to 0.
Andreas Hunter
Updated on July 27, 2022Comments
-
Andreas Hunter almost 2 years
I have custom validation rule in my controller:
$this->validate($request, [ 'currency' => [ 'required', 'numeric', 'min:0', 'max:7' ], 'price' => [ 'nullable', "required_if:currency, !=, 0", 'numeric', 'min:1', 'max:1000000' ], ], $messages);
Why work in
required_if:currency, ==, 0
and not work in thisrequired_if:currency, !=, 0
case?In my case
price
field required only whencurrency
field value not equal to0
I tired also:
required_unless,currency,0 required_unless:currency,0
-
Shamseer Ahammed almost 5 yearsNot working in my case too, but everyone suggests this format like you did.