Search code examples
javascriptregexvalidationcurrency

Regex to validate brazilian money using Javascript


I need to validate some form fileds that contain brazilian money (its name is "Real") using Javascript. It has the following format:

            0,01
            0,12
            1,23
           12,34
          123,45
        1.234,56
       12.235,67
      123.456,78
    1.234.567,89
   12.345.678,90
  123.456.789,01
1.234.567.890,12

My regex knowledge is weak, can somebody help me please?


Solution

  • Does this do what you want?

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

    That says "1 to 3 digits, optionally followed by any number of groups of three digits preceded by a period, followed by a comma and two more digits." If you want to allow the leading whitespace present in your example, add \s* to the front:

    ^\s*\d{1,3}(?:\.\d{3})*,\d{2}$
    

    As @ElRonnoco pointed out, the above regular expression accepts leading zeroes (e.g. 010.100,00). To disallow those, you may use this longer version:

    ^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0),\d{2}$
    

    To allow numbers that have no decimal part, or only one decimal digit, change it like this:

    ^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$
    

    If you want to find such strings inside longer strings rather than requiring them to match the whole thing, you can remove the ^ and $ anchors.