开发者

Basic Regular Expression for a 'generic' phone number

I need a regex (for use in an ASP .开发者_JS百科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.


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


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.


\+?[\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,}


^[0-9-+ ]+$

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


@"^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"

Here's what I use. This will handle generic phone number validation for most cases.


This one is super-generic, allowing only the characters you expect in a given phone number, including #. It ignores any format patterns.

@"^([\(\)\+0-9\s\-\#]+)$"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜