-3

I want to check a valid contact number:-

  • The number may or may not start with a + sign.
  • The number may contain space and hyphen (-) sign.
  • There should be no consecutive hyphen (-) sign.
  • There should be no other alphabets, special characters, etc.

An example of valid contact number is + 91-8341239834 or +91 033 2664 3271

The number must not exceed 20 characters.

How can I do this?

here is my code till now:-

preg_match('/^[0-9 .\-]+$/i', $number)
Saswat
  • 12,320
  • 16
  • 77
  • 156
  • For US Based phone numbers, check out: http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation/ – Clomp Feb 22 '17 at 04:50
  • @Clomp, this application is not for US based phone numbers. – Saswat Feb 22 '17 at 04:54
  • Sorry, I mistyped my quick reply. The link that I posted also contains this text in the original question: "Ideally it would handle international formats...". If you check that page out, you can find some pre-built regular expressions on it... which also handle international formats! :-) – Clomp Feb 22 '17 at 05:32

1 Answers1

1

You may want to try /^\+?(?:[0-9 ]{1,20}|([-])(?!\1))+$/ or /(\+?[0-9 ]|([-])(?!\2))*$/ if preg supports beginning and end anchor tags or possibly /\+?(?:[0-9 ]{7,20}|([-])(?!\1))+/. This regex with ^ and $ seems to satisfy all of your requirements as originally stated.

  • + 9 2344235 23244 # match
  • + 9-2344235-23244 # match
  • +923212312412424 # match
  • 1231 231 23123213 # match
  • 9--232314 # no match
  • 82foo23123bar # no match
quetzaluz
  • 1,071
  • 12
  • 17