Search code examples
javascriptregexvalidation

Comma separated mobile number Regex validation


I'm trying validation for mobile number(With country code) which is not working. Posting the validation criteria below:

Valid Numbers:

  • +18790912345 (Valid)
  • +18790112345,+18790123409 (Valid)
  • +1-2569890912345 (Valid)
  • +1-2569890912345,+939890912098 (Valid)
  • -19890123909 (Valid)

Invalid Numbers:

  • +1909890 (Invalid)
  • 9800112345 (Invalid - without country code)
  • +1 9092345690 (Invalid-Containing spaces in between)

I've tried with the below regex code's but it's not passing the criteria.

/^[+-][1-9]{0,1}[0-9-]{0,16}[,]$/

and

^[+-][0-9-]{0,16}+(,[+-][0-9-]{0,16}+)*$

What number is considered valid

A valid phone number is any number starting with either + or - and containing from 8 to 16 digits that can be optionally separated with any number of hyphens. It cannot contains whitespaces.


Solution

  • It appears you want to match numbers that contain 8 to 16 digits with optional hyphens in between the digits.

    In this case, you can use

    ^[+-]\d(?:-*\d){7,15}(?:,[+-]\d(?:-*\d){7,15})*$
    

    See the regex demo.

    Details:

    • ^ - start of string
    • [+-] - a + or -
    • \d(?:-*\d){7,15} - a digit, then seven to fifteen repetitions of zero or more hyphens and a digit (so, 8 to 16 digits all in all)
    • (?: - start of a grouping:
      • , - a comma
      • [+-] - + or -
      • \d(?:-*\d){7,15} - see above (a phone number pattern part)
    • )* - end of the grouping, zero or more repetitions
    • $ - end of string.