Max Bunker
Max Bunker

Reputation: 187

Regex for input with numbers and commas

I'm trying to limit input data.

My goal:

Test cases:

I've hade something like this but it doesn't work properly

/^\d*(,\d*)*$/.test(value)

Appreciate any help!

Upvotes: 2

Views: 1462

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can use

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

See the regex demo. Details:

  • ^ - start of string
  • (?:\d+(?:,\d+)*,?)? - an optional non-capturing group:
    • \d+ - one or more digits
    • (?:,\d+)* - zero or more sequences of a comma and one or more digits
    • ,? - an optional comma
  • $ - end of string.

Upvotes: 3

Related Questions