0

I am trying to submit a simple form with laravel. I have the following rule and when I enter '-100' or any other negative number, the validation fails.

'odds' => ['integer', 'digits_between:3,70'],

results in:

The odds field must be between 3 and 70 digits.

From the Laravel 11.x docs,

The integer validation must have a length between the given min and max.

Why is the validation failing when -100 is only 4 characters in length? I tried other integers such as -1000, -14000, -10, etc. and it seems like any negative integer gets rejected.

The field is also:

<input type="number" name="odds">

Would anyone have an idea why the laravel validation fails?

Also tried: ``'odds' => ['numeric', 'digits_between:3,70'],`

2 Answers 2

0

Use between:min,max

example : 'field_name' => ['required', 'numeric', 'between:-100,100']

https://laravel.com/docs/11.x/validation#rule-between

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

Comments

0

Create a Custom Validation Rule:

use Illuminate\Contracts\Validation\Rule;

    class DigitsBetweenInclusive implements Rule
    {
        protected $min;
        protected $max;
    
        public function __construct($min, $max)
        {
            $this->min = $min;
            $this->max = $max;
        }
    
        public function passes($attribute, $value)
        {
            $length = strlen((string) abs($value));
            return $length >= $this->min && $length <= $this->max;
        }
    
        public function message()
        {
            return 'The :attribute must be an integer with digits between ' . $this->min . ' and ' . $this->max . '.';
        }
    }

Use the Custom Rule in Your Validation:

use App\Rules\DigitsBetweenInclusive;

$request->validate([
    'odds' => ['integer', new DigitsBetweenInclusive(3, 70)],
]);

This should work properly.

1 Comment

Thanks, I experimented with this route and it does indeed work properly. I decided to choose Aakash's route since its a bit easier to implement.

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.