Inputmask - Regex currency and optional decimal places

1.4k Views Asked by At

I'm trying to create a currency Regex using the Robin Herbots Inputmask plugin and can't find a way to make it all work together I need a regex that allows precision from 2 to 10 digits and adds a comma on the thousands, like these:

1,123.00

123.12345

1,123,456.1234567890

and so on. I ended up with these regexes ^\\d{1,3}(?:,\\d{3})*$ and \d{1,99},\d{2,10}. They both achieve what I need, but separately. How to I make them both work together?

Thanks!

1

There are 1 best solutions below

3
Wiktor Stribiżew On

You can use

/^(?=(?:,?\d){1,99}(?:\.|$))\d{1,3}(?:,\d{3})*(?:\.\d{2,10})?$/

See the regex demo.

Details:

  • ^ - start of string
  • (?=(?:,?\d){1,99}(?:\.|$)) - a positive lookahead that requires 1 to 99 occurrences of an optional , followed with a digit, and then followed with either . or end of string
  • \d{1,3} - one to three digits
  • (?:,\d{3})* - zero or more occurrences of a comma and then three digits
  • (?:\.\d{2,10})? - an optional occurrence of a . and two to ten digits
  • $ - end of string.