Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation numeric with gte:1 throws exception

Why Laravel throws

InvalidArgumentException('The values under comparison must be of the same type');

exception, when input non-numeric text like 'test' on rule:

public function rules()
{
    return [
        'account_no' => 'required|numeric|gte:1'
    ];
}

When expected just not to pass validation and display message:

account_no field must be numeric

How to solve this exception?

like image 221
merdan Avatar asked Feb 21 '19 07:02

merdan


2 Answers

Merdan the field under gte validation must be greater than or equal to the given field. The two fields must be of the same type.

example let's say you have two fields

POST DATA
// $request->comparison = 1;
// $request->account_no = 20319312;

your rules should be something like

return [
    'account_no' => 'required|numeric|gte:comparison'
];
like image 96
Demonyowh Avatar answered Sep 28 '22 15:09

Demonyowh


You have to use gte, the gt and gte are added in Laravel 5.6 and latest versions and I'm not sure what laravel version you are using.

I think you can try like this:

public function rules()
{
    return [
        'account_no' => 'required|numeric|min:1'
    ];
}

OR

public function rules()
{
    return [
        'account_no' => 'required|numeric|min:0|not_in:0'
    ];
}

The min:1 is the minimum value of 1 and no negative values are allowed
The not_in:0 is the value cannot be 0.

Also you can also use regular expression for doing this job.

I hope it would be helpful. Thanks

like image 33
Inzamam Idrees Avatar answered Sep 28 '22 15:09

Inzamam Idrees