regular expression

How to use Regular expression for validating Phone Numbers in .net

Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. You can use them to constrain input, apply formatting rules, and check lengths.
You can use the System.Text.RegularExpressions.Regex class for validate any input string for any specific format.
A regular expression can easily check whether a user entered something that looks like a valid phone number. By using capturing groups to remember each set of digits, the same regular expression can be used to replace the subject text with precisely the format you want.

The following example will allow you to Input Phone Number only.

In this example we can determine whether a user entered phone number in a common format that includes 0123456789, 012-345-6789, (012)-345-6789, (012)3456789 012 3456789, 012 345 6789, 012 345-6789, (012) 345-6789, 012.345.6789 and all related combinations


using System.Text.RegularExpressions;
public static bool CheckNumber(string strPhoneNumber)
   string MatchPhoneNumberPattern = "^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$";
   if (strPhoneNumber!= null) return Regex.IsMatch(strPhoneNumber, MatchPhoneNumberPattern );
   else return false;


Import System.Text.RegularExpressions
Public Shared Function CheckPhoneNumber (ByVal strPhoneNumber As String) As Boolean
  Dim MatchPhoneNumberPattern As String = "^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"       
  If strPhoneNumber IsNot Nothing Then
     Return Regex.IsMatch(strPhoneNumber , MatchPhoneNumberPattern)
     Return False
  End If
End Function

Similarly if we want to validate phone number like xxx-xxx-xxxx format then you can use “\d{3}-\d{3}-\d{4}”.

Regular expression for phone numbers with country code:

If you want to use regular expression for validating phone or mobile numbers followed by country code. For example if you want to validating Indian mobile numbers followed by +91, then you can use the following regx:
(\+91[\-\s])\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

Now i am simplifying the above regular expression as ^(\+91[\-\s]?)\d{10}$.

Edited by Hirendra Sisodiya on 2 June, 2012.
Edited by Hirendra Sisodiya on 15 March, 2012.
Edited by Hirendra Sisodiya on 11 Jan, 2012

More on Regular Expressions