Marcio Mazzucato
Marcio Mazzucato

Reputation: 9315

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?

Upvotes: 8

Views: 12535

Answers (3)

Mark Reed
Mark Reed

Reputation: 95395

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.

Upvotes: 16

Diego Montania
Diego Montania

Reputation: 346

Complementing Mark's reply:

Who needs "." in the string and not "," to count cents. And need find the values in middle a text :

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

https://regexr.com/61166

Upvotes: 0

Joanna Derks
Joanna Derks

Reputation: 4063

I would give this regex a try:

\d+(?:\.\d{3})*?,\d{2}

What it says is:
- match digits until
a. a dot followed by 3 digits is found (and this step can be repeated several times)
b. or a comma followed by 2 digits is found

EDIT:
- thanks for the comments, I forgot about the constraint for the first value
updated regex

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

Upvotes: 3

Related Questions