2

Using JavaScript, I need to accept only numbers and commas.

The regex pattern I am using is as follows

 var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;

How do I accept commas in the above pattern So that values like 3200 or 3,200 or 3,200.00 and so are valid?

There are similar questions that only partially deal with this:

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user1339913
  • 1,017
  • 3
  • 15
  • 36

1 Answers1

4

Use the following regex:

^[-+]?(?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?$

See regex demo

The basic change here is the addition of (?:[0-9]+,)* subpattern that matches:

  • [0-9]+ - 1 or more digits
  • , - a comma

0 or more times (thanks to * quantifier).

I also used non-capturing groups so that regex output is "cleaner".

If you need to check for 3-digit groups in the number, use

^[-+]?[0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?$

See another demo

Here, (?:,[0-9]{3})* matches 0 or more sequences of a comma and 3-digit substrings ([0-9]{3}). {3} is a limiting quantifier matching exactly 3 occurrences of the preceding subpattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I know it wasn't explicitly mentioned, but I'm assuming things like `3,2,3,6,5,6.2` aren't supposed to be considered valid numbers. – James Montagne Oct 27 '15 at 13:00
  • @JamesMontagne: I updated the answer to meet that requirement. Recently, there have been various similar questions, and there was no such a restriction. – Wiktor Stribiżew Oct 27 '15 at 13:06