Laravel validation required if field not equal to
Asked Answered
D

3

7

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 this required_if:currency, !=, 0 case?

In my case price field required only when currency field value not equal to 0

I tired also:

required_unless,currency,0
required_unless:currency,0
Danseuse answered 18/12, 2018 at 12:4 Comment(1)
Why not try if currency greater than 0? i.e. currency => gt:12Gomphosis
I
17

I would suggest you use

required_unless:currency,0 according to [1]: https://laravel.com/docs/5.5/validation#rule-required-unless

Interlocutrix answered 28/10, 2019 at 20:59 Comment(0)
A
3

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.

Axe answered 18/12, 2018 at 12:18 Comment(1)
Not working in my case too, but everyone suggests this format like you did.Entirely
M
2

You can use this:

use Illuminate\Validation\Rule;

Rule::requiredIf($request->get('currency') != 0)
Mcclenaghan answered 17/9, 2021 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.