Skip to content Skip to sidebar Skip to footer

Generic Javascript Regex Validating A Positive Number With Or Without Commas As Thousand Separators And An Optional Fractional Part

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

Solution 1:

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

Solution 2:

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.

Post a Comment for "Generic Javascript Regex Validating A Positive Number With Or Without Commas As Thousand Separators And An Optional Fractional Part"