Alex
Alex

Reputation: 6665

Validating field to contain only numbers separated by commas

I'm making a form validation callback in code igniter. I'm trying to validate an input that needs to be numbers separated by commas, no spaces. For example

1,2,3,4,5 221,78,4,82,991,12 10001,10010,20010 etc

Whats the best way to validate this regex? Some other PHP wizardry?

Upvotes: 3

Views: 800

Answers (2)

agent-j
agent-j

Reputation: 27943

Here's an expression that won't require any backtracking.

/^(?:\d+(?:,|$))+$/

The non-capturing groups (?:regex) also make it faster.

Upvotes: 2

gpojd
gpojd

Reputation: 23075

Why not a regex like this?

/^(\d+,)*\d+$/

Upvotes: 5

Related Questions