0

I have following regex to validate numbers in input

var reg = /^\d+$/;

Now i want to allow ,(commas) and .(period) in number field as following will some one help me writing regex to allow following number format ?

10000000
10,000,000
10000000.00
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
d-man
  • 57,473
  • 85
  • 212
  • 296

2 Answers2

4

You may use

/^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?$/

See the regex demo

If you only need to allow 2 digits after the decimal separator, replace (?:\.\d+)? with (?:\.\d{1,2})?.

Details:

  • ^ - start of string
  • (?:\d{1,3}(?:,\d{3})*|\d+) - 2 alternatives:
    • \d{1,3}(?:,\d{3})+ - 1 to 3 digits and one or more sequences of a comma and 3 digits
    • \d+ - 1 or more digits
  • (?:\.\d+)? - an optional sequence of:
    • \. - a dot
    • \d+ - 1 or more digits
  • $
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You could use

^((\d{1,2}(,\d{3})+)|(\d+)(\.\d{2})?)$

see Regex101

or

^((\d{1,2}(,\d{3})+)|(\d+))(\.\d{2})?$

if you want 10,000,000.00 to get matched to.

nozzleman
  • 9,529
  • 4
  • 37
  • 58