0

I would like to create a regular expression in javascript to validate the annual income of a user. The problem I have is with the comma symbol, since a comma should be followed by 3 digits.

If I use this regex: (\d{3,3}\,)* then 1,000 will not match since it expects a comma at the end.

While if I use this regex: [\d]+(\,\d{3,3})* 1000,000 will match and it is not correct since it should be 1,000,000

Any help would be appreciated.

Thx in advance, Peter

PB_MLT
  • 774
  • 2
  • 11
  • 27

2 Answers2

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

BTW, I think it is better to allow the user enter any numbers they like, and then you add the commas at the appriopriate places.

kennytm
  • 469,458
  • 94
  • 1,022
  • 977
  • @SeRPRo: It will be correct if you require it to match the whole string. (OK added ^$ anyway.) – kennytm Nov 17 '11 at 10:22
  • @KennyTM Thx it works. However I don't understand this part: ?:, Kindly could you explain pls? – PB_MLT Nov 17 '11 at 10:27
  • @Spi1988: It is a [non-capturing group](http://stackoverflow.com/questions/3512471/non-capturing-group). This is like `(...)` but does not generate captures (those `$1`, `$2` things) – kennytm Nov 17 '11 at 10:33
0

How about this one:

(?:[^,\d]|^)(\d{1,3}(?:,\d{3})*)(?:[^,\d]|$)
SERPRO
  • 9,674
  • 7
  • 40
  • 61