Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Regular Expression for a 'generic' phone number

I need a regex (for use in an ASP .NET web site) to validate telephone numbers. Its supposed to be flexible and the only restrictions are:

  • should be at least 9 digits
  • no alphabetic letters
  • can include Spaces, hyphens, a single (+)

I have searched SO and Regexlib.com but i get expressions with more restrictions e.g. UK telephone or US etc.

like image 671
robasta Avatar asked Jun 13 '11 12:06

robasta


2 Answers

^\s*\+?\s*([0-9][\s-]*){9,}$

Break it down:

^           # Start of the string
  \s*       # Ignore leading whitespace
  \+?       # An optional plus
  \s*       # followed by an optional space or multiple spaces
  (
     [0-9]  # A digit
     [\s-]* # followed by an optional space or dash or more than one of those
  )
   {9,}     # That appears nine or more times
$           # End of the string

I prefer writing regexes the latter way, because it is easier to read and modify in the future; most languages have a flag that needs to be set for that, e.g. RegexOptions.IgnorePatternWhitespace in C#.

like image 69
configurator Avatar answered Sep 20 '22 10:09

configurator


It's best to ask the user to fill in his country, then apply a regex for that country. Every country has its own format for phone numbers.

like image 23
Roy Dictus Avatar answered Sep 19 '22 10:09

Roy Dictus