Regex to validate brazilian money using Javascript

杀马特。学长 韩版系。学妹 提交于 2019-12-22 09:18:48

问题


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?


回答1:


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}$

EDIT: 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}$

EDIT 2 The above regular expressions all match a string containing a single monetary amount and nothing else. It's not clear from the question if that's the intent.

EDIT 3 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})?$



回答2:


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}


来源:https://stackoverflow.com/questions/10300930/regex-to-validate-brazilian-money-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!