Laravel validation required if field not equal to

10,184

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.

Share:
10,184
Andreas Hunter
Author by

Andreas Hunter

Updated on July 27, 2022

Comments

  • Andreas Hunter
    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 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
    
  • Shamseer Ahammed
    Shamseer Ahammed almost 5 years
    Not working in my case too, but everyone suggests this format like you did.