skip to Main Content

On laravel 11 site I need to check decimal values from 0 till 100(with 2 decimals possible) and I do it with rules :

['required', 'numeric', 'between:0,100'],

OR

required|numeric|min:0.01|max:100

but both not works. Which rules are valid ?

"laravel/framework": "^11.9",

Thanks in advance!

3

Answers


  1. [
        'required',
        'numeric',
        'regex:/^d{1,2}(.d{1,2})?$|^100(.00?)?$/',
        'between:0,100',
    ]
    
    • regex:/^d{1,2}(.d{1,2})?$|^100(.00?)?$/: This regular expression allows numbers from 0 to 100, with up to two decimal places.

      • ^d{1,2}(.d{1,2})?$: Matches numbers from 0 to 99.99.
      • |^100(.00?)?$: Allows the number 100, optionally followed by .0 or .00.
    • between:0,100: Ensures that the number is within the range 0 to 100.

    Login or Signup to reply.
  2. You can use this, too

    $request->validate([
        'your_field_name' => [
            'required',
            'numeric',
            'between:0,100',
            'regex:/^d{1,2}(.d{1,2})?$/'
        ],
    ], [
        'your_field_name.regex' => 'The :attribute must be a number with up to two decimal places.',
    ]);
    
    Login or Signup to reply.
  3. You can do this using regex way

    $request->validate([
    'field_name' => [
        'required',
        'numeric',
        'between:0,100',
        'regex:/^d*(.d{1,2})?$/',
        ],
     ]);
    

    If you need this without using regex, you can follow the steps below

    Create Custom Validation Rule

    php artisan make:rule DecimalPrecision
    

    Implement Rule Logic

    namespace AppRules;
    
    use IlluminateContractsValidationRule;
    
    class DecimalPrecision implements Rule
    {
        public function passes($attribute, $value)
        {
            return is_numeric($value) && $value >= 0 && $value <= 100 && preg_match('/^d+(.d{1,2})?$/', $value);
        }
    
        public function message()
        {
            return 'The :attribute must be a number between 0 and 100 with up to 2 decimal places.';
        }
    }
    

    Use Custom Rule

    use AppRulesDecimalPrecision;
    
    $request->validate([
        'value' => ['required', 'numeric', new DecimalPrecision()],
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search