Monday, July 13, 2009
If you have a database having phone numbers in various formats, you would want to display them in a consistent format. A solution to display phone numbers in a standard format without worrying about the format in the database is to use regular expressions to format the phone numbers.
For implementing this into ASP.NET pages create a class in the App_Code folder of your web application. Create a static(C#) or shared(VB.NET) method in this class which gets the value of the phone number field as object to handle null values of phone numbers in the database. The code for this function is given below:
// C#
public class CommonFunctions
{
public static string FormatPhone(object phoneNo)
{
string formattedPhone = phoneNo.ToString;
// Extracting numbers from the string
formattedPhone = Regex.Replace(formattedPhone, "[^0-9]", "");
// The format is in third parameter of the replace function
formattedPhone = Regex.Replace(formattedPhone, "(\\d{3})(\\d{3})(\\d{4})", "($1) $2-$3");
return formattedPhone;
}
}
' VB.NET
Public Class CommonFunctions
Shared Function FormatPhone(ByVal phoneNo As Object) As String
Dim formattedPhone As String = phoneNo.ToString
' Extracting numbers from the string
formattedPhone = Regex.Replace(formattedPhone, "[^0-9]", "")
' The format is in third parameter of the replace function
formattedPhone = Regex.Replace(formattedPhone, "(\d{3})(\d{3})(\d{4})", "($1) $2-$3")
Return formattedPhone
End Function
End Class
The above function first abstracts all the digits from the phone number by using the "[^0-9]" regular expression; all characters which are not numbers are replaced by "". Then the phone numbers are broken into three groups using "(\d{3})(\d{3})(\d{4})" and the groups are then displayed as "($1) $2-$3". Thus, a phone number such as 123.456-7890 will first be converted into 1234567890 and then formatted as (123) 456-7890. You can modify the display format by changing the second replace function.
You can use this method from any ASP.NET data bound field as follows:
<%# CommonFunctions.FormatPhone(Eval("Phone")) %>
Though this example shows the use of this function for ASP.NET pages, it can be used for any .NET based application.