Skip to content
Advertisement

How to validate integers and max float digits in one rule in laravel

Hey guys I need to validate something on my laravel application and I don’t know how.

So if the user introduces 1234.55 it should allow it, because it have only 5 numbers, but if the user introduces 12345678.55 must reject!

What I have until now.

return [
    'max_debit' => 'required|numeric|min:0'
];

I tried to use digits_between, but when I use this, the validation doesn’t allow float numbers.

So the rule should match:

  • Integer numbers
  • Float numbers -> All greater or equal to 0
  • Max digits: 9
  • Accept: 1234.55
  • Reject: 12345678.55

Advertisement

Answer

You can do it with the regex rule: https://laravel.com/docs/master/validation#rule-regex

'max_debit' => [
    'required',
    'max:9',
    'regex:/^(([0-9]*)(.([0-9]+))?)$/',
],

With the max you define a maximum of 9 characters. If you want to limit the digits after the period, you can add the {0,2} group where 0 stands for zero digits and 2 for max 2 digits after the period:

/^(([0-9]*)(.([0-9]{0,2}+))?)$/

Answer based on this answer: https://stackoverflow.com/a/23059703/6385459

Is this what you’re looking for?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement