Home > front end >  Allow only numeric and float values with validation in Laravel
Allow only numeric and float values with validation in Laravel

Time:09-18

I have a field days in my model, now I want to only save integer or float values in this column.

Values can be like:

  • 1
  • 2
  • 0.5
  • 2.5

I tried to use numeric but then it is not allowing me to input float values:

$this->validate($request, [
    'days' => 'required|numeric|min:1|max:50',
]);

Any help is highly appreciated.

Thanks

CodePudding user response:

You can use closures if no validation rule helps you.

So, first try this:

'days' => 'required|numeric|min:0|max:50',

If it is not working, we can use closures:

'days' => [
    'required',
    'numeric',
    function ($attribute, $value, $fail) {
        if ($value <= 0) {
            $fail($attribute.' must be greater than 0.');
        }
    },
    'max:50',
],

Have in mind that numeric validation, uses is_numeric built-in PHP function.

CodePudding user response:

You can try custom validation rules for your case. Example:

'days' => 'required|regex:/^\d*(\.\d{2})?$/'
  • Related