Search code examples
javascriptregexcurrency

Javascript regex for money with max length


I want validate a money string with numbers max length 13 with 2 decimal. I have a comma as decimal separator and a period as a thousands separator.

I have this regex:

/^(\d{1}\.)?(\d+\.?)+(,\d{2})?$/

For sintax is valid but not for max length. What I need to add to this regex?

For example, these strings must be valid:

1.000.000.000.000
1.000.000.000.000,00
1
1,00
123,45

And these must be invalid:

10.000.000.000.000
10.000.000.000.000,00
10.000.000.000.000.000
10.000.000.000.000.000,00

Solution

  • You may use this regex for validation:

    ^(?=[\d.]{1,17}(?:,\d{2})?$)\d{1,3}(?:\.\d{3})*(?:,\d{2})?$
    

    RegEx Demo

    RegEx Details:

    • ^: Start
    • (?=[\d.]{1,17}(?:,\d{2})?$): Lookahead to match dot or digit 1 to 17 times followed by optional comma and 2 digits
    • \d{1,3}: Match 1 to 3 digits
    • (?:\.\d{3})*: Match . followed by 3 digits. Repeat this group 0 or more times
    • (?:,\d{2})?: Match optional , followed 2 decimal digits
    • $: End