Need a regular expression to validate number with comma separator. 1,5,10,55 is valid but 1,,,,10 is not valid.
Asked
Active
Viewed 2.8k times
9
-
As a side note - a regex can validate your input, but not parse it (unless you `match` for `\d+`). If your next step is to split the string you might as well split it before validating it. Next, what where does jQuery fit it? Is it a validation plugin? – Kobi Aug 11 '10 at 07:17
-
Yes I want to validate a string using jquery validation plugin . – Suvonkar Aug 11 '10 at 09:00
3 Answers
22
This should do it:
^\d+(,\d+)*$
The regex is rather simple: \d+
is the first number, followed by optional commas and more numbers.
You may want to throw in \s*
where you see fit, or remove all spaces before validation.
- To allow negative numbers replace
\d+
with[+-]?\d+
- To allow fractions: replace
\d+
with[+-]?\d+(?:\.\d+)?

Kobi
- 135,331
- 41
- 252
- 292
12
Here are the components of the regex we're going to use:
\d
is the shorthand for the digit character class+
is one-or-more repetition specifier*
is zero-or-more repetition specifier(...)
performs grouping^
and$
are the beginning and end of the line anchors respectively
We can now compose the regex we need:
^\d+(,\d+)*$
That is:
from beginning...
| ...to the end
| |
^\d+(,\d+)*$ i.e. ^num(,num)*$
\_/ \_/
num num
Note that the *
means that having just one number is allowed. If you insist on at least two numbers, then use +
instead. You can also replace \d+
with another pattern for the number to allow e.g. sign and/or fractional part.
References
Advanced topics: optimization
Optionally you can make the brackets non-capturing for performance:
^\d+(?:,\d+)*$
And if the flavor supports it, you can make all repetition possessive in this case:
^\d++(?:,\d++)*+$
References

polygenelubricants
- 376,812
- 128
- 561
- 623
-1
^[0-9]*(,){1}[0-9]*/
try this

Sachin R
- 11,606
- 10
- 35
- 40
-
3Well, `{1}` is redundant, and so is the capturing group. This is the same as `\d*,\d*` - it must have a single comma, with optional digits around it; not quite the request here. It accepts `,`, `12,34`, `,34`, and rejects `1`, `1,2,3`. – Kobi Aug 11 '10 at 07:08