简体   繁体   中英

Using regex to validate mask and limit range in currency

I am working on a feature on my application and now have a requirement that need a regex to validate the mask typed by the user (it is ok) and limit the range typed. For example, if I type:

100,00 - can pass
50,00 - can pass
100.000,00 - can pass
100.000,01 - more than 100k not pass

Now, I have my regex working to validate the mask, but I can not limit the range...

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

Anyone knows how can I achieve this limitation?

You need to validate the 100.000,00 part separately. Also, remember that \. matches a dot, and that in your current regex, you allow an unlimited number of repetitions, so 100.000.000.000,00 currently passes.

Try this:

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

Test it live on regex101.com .

Explanation:

^                   # Start of string
\$?                 # Match optional dollar sign
(?:                 # Group: Match either
 100\.000,00        # 100.000,00
|                   # or
 (?:                # Group: Match either
  [1-9]\d?\.\d{3}   # a number between 1.000 and 99.999
 |                  # or
  [1-9]\d{0,2}      # a number between 1 and 999  
 |                  # or
  0                 # 0
 )                  # End of inner group
 \,\d{1,2}          # Match , and one or two digits
)                   # end of outer group
$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM