How to Format a Phone Number in C#

Last Updated Jul 29, 2022
Brian Wu

Brian Wu is an SEO marketer with enjoys testing and playing around with APIs in his free time.

Table of Contents:

Although there is an international standard for formatting phone numbers, phone formats may vary from region to region. Sometimes the short format of telephone numbers may be used within the same region, although this is not recommended. In this article, we will talk about why it is important to format telephone numbers correctly and how to do it using C#. We will look at different ways to format and validate phone numbers.

What Are the Correct Phone Number Formats?

A phone number is a unique address for switching phone calls using the destination code routing system. Typically, the phone number is divided into three parts:

  • Country code specifies the country in which the phone number is located.
  • City code specifies the city in which the phone number is located.
  • Subscriber number.

Sometimes when writing a telephone number, some of its parts are considered optional. For example, if the calling user and the called one are in the same country, then the country code can be omitted when dialing.

There are also short reserved telephone numbers that do not follow the usual addressing format based on country or area codes.

There is an international standard according to which telephone numbers are formatted. In addition, different countries may have additional rules that require prefix digits to be added to telephone numbers. For example, in the United States, a phone number has four parts: a country code, a three-digit area code, a three-digit phone exchange code, and a four-digit line number. EU countries use a standard three-part phone format. The number of digits in a phone number may vary depending on the country, area, and population.

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

Why Should You Format Phone Numbers Correctly?

Although within the same city or country, you can use a short form of the telephone number without specifying the city and country code, it is recommended that you save it with all its parts. This is important for business for several reasons.

  • If not all telephone numbers conform to the globally unique number format, then the process of deciphering the dialing pattern in the list of them can be problematic.
  • Using the full format of telephone numbers, you can obtain additional information about the location and carrier of the subscriber.
  • Before storing a phone number, it is important to check that area codes or line numbers are valid so that you do not hold a telephone number that is unwanted or invalid.

How to Format a String as a Telephone Number in C#?

When filling out a form to enter a telephone number, users can use different formats. After that, the system receives the entered value as a string. For further work with received telephone numbers, you need to format strings in a way that will be understandable to the system. 

First, you need to clear the received phone number from all nonnumeric characters, leaving only numbers. It is very convenient to use regular expressions for this. To do this, you need to create a Regex class variable that will match a string that contains only numbers.


Regex regex = new Regex(@"[^\d]");

Then, using the Replace() method, you need to replace the phone number with a new one, using the format defined in the regular expression.


phone = regex.Replace(phone, "");

Then, you can use several different options to format the string as a phone number in C#.

Using Regex

One way to format a string as a telephone number in C# is to use regular expressions. To do this, use the Replace() method of the Regex class. This method replaces the incoming telephone number string that matches the specified regular expression with a string with the specified format.


phone = Regex.Replace(phone, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");

The complete code for creating a formatted string in C# using regular expressions is as follows:


public static string FormatPhoneNumber(string phone)
{
    Regex regex = new Regex(@"[^\d]");
    phone = regex.Replace(phone, "");
    phone = Regex.Replace(phone, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
    return phone;
}

Using method ToString()

You can format a string as a telephone number very simply by using the overridden ToString() method of the Object class. To start enter the phone number format to which you want to cast all numbers. For example, you can use the following format:


string phoneFormat = "###-###-####";

Then it remains to convert the string with the phone number into a 64-bit integer format, and then into a string value with the specified format.


phone = Convert.ToInt64(phone).ToString(format);

The phone number formatting function using the ToString() method looks like this:


public static string FormatPhoneNumber(string phone)
{
    Regex regex = new Regex(@"[^\d]");
    phone = regex.Replace(phone, "");
    string format = "###-###-####";
    phone = Convert.ToInt64(phone).ToString(format);
    return phone;
}

Similarly, you can use the static method String.Format().

How to Validate Phone Numbers in C#?

After formatting phone numbers, it is important to check if they are valid. As we mentioned above, phone number formats may differ both in different countries and within the same country. Therefore, it is important to find an efficient solution that allows you to check all valid phone number formats.

Using Regex

Using regular expressions is a good way to validate standard phone number formats. You only need to write a few lines of code to do this.


public static string regex = @"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$";

public bool IsCorrectPhoneFormat(string phone)
{
    if (!string.IsNullOrEmpty(phone)) 
        return Regex.IsMatch(phone, regex);
    return false;
}

public static void Main()
{
    IsCorrectPhoneFormat("14234567891");
}

This method allows you to check standard phone number formats such as 0123456789, 012-345-6789, and (012) -345-6789. If your system supports other formats, you only need to replace the regular expression to validate them.

The disadvantage of this method is that regular expressions are quite difficult to understand.

Using AbstractAPI Phone Number Validation API

An alternative way to validate phone numbers is to use a special API that allows you to perform validation quickly and effortlessly. 

One such API is the lightweight and ultra-fast Abstract Phone Validation API, which allows you to instantly validate telephone numbers. To do this, you just need to make one request, the parameters of which will be your unique API key and the phone number to be validated.


https://phonevalidation.abstractapi.com/v1/?api_key= YOUR_UNIQUE_API_KEY&number=14234567891

If the specified phone number is valid, you will receive the following response:


{
  "number": "14234567891",
  "is_valid_number": true,
  "local_format":"14234567891",
  "international_format": "+14234567891",
  "country_name": "United States of America",
  "country_code": "US",
  "country_prefix":"+1",
  "registered_location": "San Francisco, CA",
  "carrier":"Verizon USA",
  "line_type": "Mobile",
}

A huge advantage of using the Abstract Phone Validation API is that it allows you to get additional information about phone numbers such as the international format, country name, and carrier. In addition to validating the format, the Abstract API allows you to check if a phone number exists and is maintained, which you can not do with regular expressions.

Using Abstract Phone Validation API allows you to not write validation code from scratch, which simplifies the development process and improves productivity.

FAQ

What is the correct phone number format?

The correct phone number format follows the international standard. In addition, some countries may have additional rules for formatting phone numbers. It is usually divided into three parts: country code, area code, and subscriber number.

How to write a phone number in international format?

A phone number in international format includes a plus sign (+), country code, area code, and local phone number. For example, if a phone number in the United States has a country code of "1", an area code of "408", and a phone number of "123-4567", the correct international format would be +1 408 123 4567.

How can I check if a phone number is valid?

To check the validity of a phone number, you can write code from scratch or use a ready-made software solution. One such solution is the Abstract Phone Validation API, which allows you to easily and quickly validate a phone number format, and provides other useful information.

Validate phone numbers instantly using Abstract's phone verification API.

Get started for free
Validate phone numbers instantly using Abstract's phone verification API.
Get started