Comma Separated Numbers Regex

I am trying to validate a comma separated list for numbers 1-8.

i.e. 2,4,6,8,1 is valid input.

I tried [0-8,]* but it seems to accept 1234 as valid. It is not requiring a comma and it is letting me type in a number larger than 8. I am not sure why.


[0-8,]* will match zero or more consecutive instances of 0 through 8 or ,, anywhere in your string. You want something more like this:

^[1-8](,[1-8])*$

^ matches the start of the string, and $ matches the end, ensuring that you're examining the entire string. It will match a single digit, plus zero or more instances of a comma followed by a digit after it.


/^\d+(,\d+)*$/
  • for at least one digit, otherwise you will accept 1,,,,,4