0

I want to create regex which should have following things:

  • The regex is for validating phone numbers so it should have minimum length 10 digits and maximum length of 12 digits except special symbols like +, - and space.
  • Plus sign only allowed at start.

I tried below regex but not working for me.

^\+[-0-9 ]\d{10,12}$

Please advice me how I can achieve this. Below are few examples for which I need to write regex:

+12 1234567890
+12 12 345 567 89
+12 123-455-6789
+9712345567

In the question which was said to be a duplicate, do not have any information regarding restricting the length upto 12 numbers.

Sawant Akshay
  • 2,654
  • 3
  • 14
  • 15
  • 1
    possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – rlemon Sep 07 '15 at 11:29

2 Answers2

1

You can use the following regex to validate your phone numbers:

^\+?(?![^ -]*[ -]{2})(?=(?:[ -]*\d){10,12}$)\d[\d -]*\d$

See demo (Note that \n is added to the negated character class since it is a demo with multiline flag.)

The regex validates a string if it matches the following:

  • ^\+? - starts with an optional +
  • (?![^ -]*[ -]{2}) - there are no consecutive spaces of hyphens
  • (?=(?:[ -]*\d){10,12}$) - total digit number is from 10 to 12 (not counting spaces or hyphens)
  • \d[\d -]*\d$ - match if string starts and ends with a digit, and may have spaces or hyphens inside.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Where did the *no consecutive specials* rule come from? It's not in the question. It also doesn't say the first and last characters must be digits. If spaces and hyphens aren't significant, it shouldn't matter where they appear. – Alan Moore Sep 07 '15 at 11:33
  • @AlanMoore: I cannot imagine a phone number not following those rules. Can you? – Wiktor Stribiżew Sep 07 '15 at 11:36
  • I can't imagine a system the *requires* those rules. Does the presence and placement of those characters serve to differentiate one input from another? The OP didn't say so--in fact, he didn't even say they're phone numbers! It looks to me like you're reading stuff into the question based on your experience answering similar questions. Or maybe just to make the question more interesting. ;) – Alan Moore Sep 07 '15 at 12:12
1

This regex allows + at start and - or space between digits.

^\+?[0-9](?:[- ]?[0-9]){9,11}$

Last character needs to be a digit.