1

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

7
  • @Pradeep : i tried your solution but ity is not allowing me to enter values like : 0.5 Commented Aug 31, 2021 at 7:51
  • just remove the min:1 Commented Aug 31, 2021 at 7:53
  • 1
    @Pradeep: shouldd i use only required|digits bacause currently i'm using required|digits_between:0,100 Commented Aug 31, 2021 at 7:56
  • try with this 'required|numeric|min:0|max:50' Commented Aug 31, 2021 at 8:01
  • @Pradeep I tried this but it is not working Commented Aug 31, 2021 at 8:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

I would not recommend using a regex for such a simple thing, it is overkill for someone that could not know regex at all compared to my answer. Also, it is less performant (even though this is a simple number to check).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.