skip to Main Content

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’],`

3

Answers


  1. Use between:min,max

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

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

    Login or Signup to reply.
  2. Create a Custom Validation Rule:

    use IlluminateContractsValidationRule;
    
        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 AppRulesDigitsBetweenInclusive;
    
    $request->validate([
        'odds' => ['integer', new DigitsBetweenInclusive(3, 70)],
    ]);
    

    This should work properly.

    Login or Signup to reply.
  3. That’s because the minus sign is not a digit.
    Please use @Kavinud’s solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search