Summer Sale! All accounts are 50% off this week.

cupcakedream's avatar

What's The Best Way To Validate A Number With A Dollar Sign ($)

Hey All -

I feel like this should be simple... I'm passing a number to Laravel's request()->validate() function. Something like $5,560.50 and I want Laravel to make sure it's a valid amount. I can't use numeric because it's technically not a number. What should I do?

Thanks,

Mike

0 likes
2 replies
click's avatar

You could do this with a regex validation. But it depends on what you see as a valid value.

Are spaces allowed? Is a thousands separator mandatory? Is the decimal separator mandatory and always a dot? Etc.

I've made an example for you: https://regex101.com/r/W0AikC/2 where you can test out a few values. Click on 'Switch to unit tests(7)' right below the regular expression to test a few use cases i've added.

And the Laravel regex validation looks like:

Validator::make($data,
    [
         'currency' => 'regex:^$\d{1,3}(?:,?\d{3})*(?:\.\d{2})?$',
    ]
);

In words it says:

  • start with a dollar sign
  • followed by 1, 2 or 3 decimals
  • followed by an optional group(s) of 3 decimals separated with a comma (thousand separator)
  • followed by an optional group of 2 decimals prefixed with a dot (decimal separator)
Cronix's avatar

The simplest would be to not include the dollar sign in the input. Show it before the field and only allow numeric input.

$<input type="number" min="0.01" max="10000">  // allow .01-10000
1 like

Please or to participate in this conversation.