Home > Software design >  Require greater than zero if other field is zero in Laravel
Require greater than zero if other field is zero in Laravel

Time:01-24

I have two number text fields:

<input type="number" name="amount_1">
<input type="number" name="amount_2">

I need to validate them where at least one of them has a value of at least 1.

I currently have this on my validation:

'amount_1' => 'required_unless:amount_2,0',
'amount_2' => 'required_unless:amount_1,0',

With the code above, i do not see error message if any of the two field has a value of 1, which is correct. But I do not have error message if both of them have 0 value.

What I need is to have the other textbox to have a value of at least 1 if the other has a value of 0.

If both have a value of at least 1 it is fine also.

is this possible?

CodePudding user response:

Use a custom validation rule:

Assuming it's a one-off for your application, it's probably easiest to use a closure:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'amount_1' => function ($attribute, $value, $fail) use ($request) {
        if ($value   $request->input('amount_2') <= 0) {
            $fail('Amount 1 or Amount 2 must be more than 0');
        }
    },
]);
  •  Tags:  
  • Related