DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Validate comma separated numbers

I have to check if a string has this pattern: 1,2,10,11.

The rules are:

What I have tried is:

What I don't know is how to test the entire string. All my tests only checks a part of it(e.g 1,) not the entire string.

Note: I'm using JavaScript test() function. Don't know if is the right one, but I believe that it is.

Upvotes: 1

Views: 3436

Answers (2)

alpha bravo
alpha bravo

Reputation: 7948

per OP

The number must be followed by a comma

so a little modification to anubhava's pattern/^(\d{1,2},)+\d{1,2}$/ otherwise it will validate single or double digits only like 1 or 10

Upvotes: 1

anubhava
anubhava

Reputation: 785146

You can try this regex:

/^(\d{1,2},)*\d{1,2}$/

Details:

^           - Line start
\d{1,2}     - 1 or 2 digit number
\d{1,2},    - 1 or 2 digit number followed by a comma
(\d{1,2},)* - 0 or more of 1/2 digit number followed by a comma character
\d{1,2}     - 1 or 2 digit number
$           - Line end

Regular expression visualization

Upvotes: 6

Related Questions