Andreas Hunter
Andreas Hunter

Reputation: 5004

Laravel validation required if field not equal to

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

Upvotes: 8

Views: 22948

Answers (3)

Negar Javadzadeh
Negar Javadzadeh

Reputation: 387

You can use this:

use Illuminate\Validation\Rule;

Rule::requiredIf($request->get('currency') != 0)

Upvotes: 2

D Malan
D Malan

Reputation: 11414

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.

Upvotes: 3

Abednego
Abednego

Reputation: 657

I would suggest you use

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

Upvotes: 18

Related Questions