Code Snippet: Format Phone Numbers using String.Format
page 1 of 1
Published: 13 Sep 2005
Unedited - Community Contributed
Abstract
The String.Format method provides a simple way to format data received from the user. Steven Swafford provides an example of using String.Format to display a telephone number in a country-specific format.
by Steven Swafford
Feedback
Average Rating: 
Views (Total / Last 10 Days): 89588/ 134

Introduction

I am sure that you have been in a position where you need to format data input, such as a phone number, for storage or retrieval. The String.Format method makes this very simple. While you could of course use other mechanisms such as regular expressions, my intent here is to demonstrate the simplicity of using the Format method of the String Class.

Demonstration

For the purpose of this code snippet, I am using a drop-down list which determines the format type based on the selected country.

Figure 1: Example Web Form

As you can see, the country selected will determine the format of the input received from the user. Let us take the good ol' USA as an example. Say we want the following format: (xxx) xxx-xxxx. With four lines of code this can be accomplished.

Listing 1: USA Telephone Format Code

string.Format("({0}) {1}-{2}",
    phoneNumber.Substring(0, 3),
    phoneNumber.Substring(3, 3),
    phoneNumber.Substring(6));

Figure 2: Formatted USA Telephone Number

That is all there is to formatting the number 9055551101 as (905) 555-1101.

Sample Code

Since a drop-down list is used to determine the country, it is best to use a switch statement. The FormatTelephoneNumber() method takes two parameters.

  1. phoneNumber
  2. country

Listing 2: FormatTelephoneNumber() Method

/// <summary>
/// Formats the telephone number.
/// </summary>
/// <param name="phoneNumber">The phone number.</param>
/// <param name="country">The country.</param>
public void FormatTelephoneNumber(string phoneNumber, string country)
{
    switch (country)
    {
        case "China":
            if (phoneNumber.Length != 10)
            {
                lblPhoneNumber.Text = "China numbers must contain 10 digits!";
                lblPhoneNumber.Visible = true;
            } // if (txtPhoneNumber.Text)
            else
            {
                lblPhoneNumber.Text = "China Local Number: " +
                    string.Format("({0})-{1}",
                    phoneNumber.Substring(0, 2),
                    phoneNumber.Substring(2, 8));
                    lblPhoneNumber.Visible = true;
            } // else
            break;
        case "United Kingdom":
            if (phoneNumber.Length != 11)
            {
                lblPhoneNumber.Text = "United Kingdom numbers must contain 11 digits!";
                lblPhoneNumber.Visible = true;
            } // if (txtPhoneNumber.Text)
            else
            {
                lblPhoneNumber.Text = "United Kingdom Local Number: " +
                    string.Format("{0}-{1}-{2}",
                    phoneNumber.Substring(0, 5),
                    phoneNumber.Substring(5, 3),
                    phoneNumber.Substring(8));
                    lblPhoneNumber.Visible = true;
            } // else
            break;
        case "United States":
            if (phoneNumber.Length != 10)
            {
                lblPhoneNumber.Text = "United States numbers must contain 10 digits!";
                lblPhoneNumber.Visible = true;
            } // if (txtPhoneNumber.Text)
            else
            {
                lblPhoneNumber.Text = "United States Local Number: " +
                    string.Format("({0}) {1}-{2}",
                    phoneNumber.Substring(0, 3),
                    phoneNumber.Substring(3, 3),
                    phoneNumber.Substring(6));
                    lblPhoneNumber.Visible = true;
            } // else
            break;
        case "Venezuela":
            if (phoneNumber.Length != 11)
            {
                lblPhoneNumber.Text = "Venezuela numbers must contain 11 digits!";
                lblPhoneNumber.Visible = true;
            } // if (txtPhoneNumber.Text)
            else
            {
                lblPhoneNumber.Text = "Venezuela Local Number: " +
                    string.Format("({0})-{1},{2},{3}",
                    phoneNumber.Substring(0, 4),
                    phoneNumber.Substring(4, 3),
                    phoneNumber.Substring(7, 2),
                    phoneNumber.Substring(9));
                    lblPhoneNumber.Visible = true;
            } // else
            break;
        default:
            lblPhoneNumber.Text = "An unknown error occurred. " + 
                "Please verify your entry and try again. " +
                "If the problem persists, please contact your system administrator.";
            lblPhoneNumber.Visible = true;
            break;
    }
}

To put all of this together, you will recall from Figure 1 that I have a button on the Web Form. Here I have established an OnClick event handler that performs three actions.

  1. Obtains the country selection and telephone number value.
  2. Validates that a country was in fact selected.
  3. Calls FormatTelephoneNumber(), passing in the two required parameters.

Listing 3: btnSubmit_Click Event

/// <summary>
/// Handles the Click event of the btnSubmit control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing
/// the event data.</param>
private void btnSubmit_Click(object sender, System.EventArgs e)
{
    lblPhoneNumber.Text = null;
    string phoneNumber = txtPhoneNumber.Text;
    string country = ddlCountries.SelectedValue;
    if (country == "Select Format")
    {
        lblPhoneNumber.Text = "You must select a country!";
        lblPhoneNumber.Visible = true;
        return;
    } // if (country)
    FormatTelephoneNumber(phoneNumber, country);
}

Conclusion

As you can clearly see, the String.Format method is simple and straight forward in the case of this code snippet. I hope that you find this snippet useful and try applying this method to other types of string such as Social Security Numbers.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 8/23/2014 7:25:06 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search