Laravel: Validating a number greater than zero is failing

MrCujo picture MrCujo · Sep 19, 2018 · Viewed 34.2k times · Source

I gotta validate a price field which needs to be greater than zero (0.01 is valid) so I have the following validation:

$request->validate([
            'product_price' => 'required|numeric|gt:0',
        ]);

The problem is that when I enter a string in the 'product_price' field I'm getting an error:

InvalidArgumentException The values under comparison must be of the same type

why is that? I mean, I'm checking that it should be numeric before even checking that it's > 0

Answer

Tharindu Thisarasinghe picture Tharindu Thisarasinghe · Sep 19, 2018

gt, gte, lt and lte are added in Laravel 5.6 and later versions, I'm guessing that must be the reason for you get the error. (It's working for me though.)

I think you can try like this

$request->validate([
    'product_price' => 'required|numeric|min:0|not_in:0',
]);

min:0 make sure the minimum value is 0 and no negative values are allowed. not_in:0 make sure value cannot be 0. So, combination of both of these rules does the job.

You can define meaningful error messages for certain rule. (You can achieve the same result using regular expressions as well.)