Home > front end >  Regex for input with numbers and commas
Regex for input with numbers and commas

Time:10-02

I'm trying to limit input data.

My goal:

  • only two symbols per input allowed: numbers and a comma
  • first symbol only number (zero or more)
  • amount of numbers is unlimited (zero or more)
  • a dangling comma is allowed but only one

Test cases:

  • 1,2,4 - ок
  • 1221,212,4121212 - ок
  • ,2,3 - not ок
  • 1,2,3, - ок
  • 11,21111,31111, - ок

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

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

Appreciate any help!

CodePudding user response:

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.
  • Related