Basic Regular Expression for a 'generic' phone number

18,474

Solution 1

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.

Solution 2

^\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#.

Solution 3

\+?[\d- ]{9,}

This will match numbers optionally starting with a plus and then at least nine characters long with dashes and spaces.

Although this means that dashes and spaces count towards the nine characters. I would remove the dashes and spaces and then just use

\+?[\d]{9,}

Solution 4

^[0-9-+ ]+$

<asp:RegularExpressionValidator runat="server" id="rgfvphone" controltovalidate="[control id]" validationexpression="^[0-9-+ ]+$" errormessage="Please enter valid phone!" />
Share:
18,474
robasta
Author by

robasta

Updated on June 13, 2022

Comments

  • robasta
    robasta almost 2 years

    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.

  • GalacticCowboy
    GalacticCowboy almost 13 years
    Exactly right - there is no standard, so it's difficult to provide a regex that will match across the board without making it so generic that it can't prevent invalid entries.
  • robasta
    robasta almost 13 years
    I wanted a flexible format. Here (SA) there is no strict phone format (e.g 0711231234, 071 123 1234, 071-123-1234, (071) 123 1234 are acceptable). I guess a masked edit box is the best way forward.
  • configurator
    configurator almost 13 years
    Note that this is a very lax approach; it would accept numbers like +--1---2345 - - - 678 9 - , and only checks that there's a minimum of nine digits and that a plus only appears at the start. I think that's what you wanted though.
  • Roy Dictus
    Roy Dictus almost 13 years
    In that case, I suppose a regex that would accept exactly 10 digits and filtered out (, ), and whitespace would do.