Guides
Last Updated Aug 04, 2023

How to Validate a Phone Number in C#

Emma Jagger

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Keeping the customer database clean with a valid phone number is crucial for your business. You can’t achieve success with fake numbers or without basic phone number validation. Your marketing campaign will fail completely. Contacting a registered and active phone number can make a real difference. It will enable you to find genuine clients and land big opportunities. There are different ways to validate phone numbers in C#. You can use Regex or the libphonenumber-csharp library to validate phone number format and ensure proper phone number input. Also, you can utilize a phone number validation API. But which is the easiest method? In this post, you will find all the details.

Let’s send your first free
API
Phone Validation API
call
See why the best developers build on Abstract
Get your free api

Validate phone number with a simple Regex in C#

Phone numbers have different formats, which varies from an international phone number to North American phone numbers. For example, an Indian phone number starts with +91. On the other hand, US numbers begin with +1. Some of the countries share the same country code. For example, the country code of the USA, Canada, and Caribbean islands is +1. Also, the format can vary within the same country. Overall, there are a lot of complexities. This can make the process of validating phone numbers the user enters very challenging. Is there any effective way of performing the verification?

You can validate the phone number in C# easily by utilizing a simple Regex (or regular expressions), like this:


^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

By using this Regex, you can validate phone numbers in common formats, like 0123456789, 012-345-6789, and (012) -345-6789.

Let’s utilize this Regex in C#.

How can you validate phone numbers with a simple Regex in C#?

1. First, you have to use System and System.Text.RegularExpressions namespaces.


using System;
using System.Text.RegularExpressions;

2. Now, you have to create a static class, called PhoneNumber. Also, you have to define the Regex and add the if-else statement to verify the given phone number.


public static class PhoneNumber
{
  // Regular expression used to validate a phone number.
  public const string motif = @"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$";

  public static bool IsPhoneNbr(string number)
  {
    if (number != null) return Regex.IsMatch(number, motif);
    else return false;
  }
}

3. Create a new class, called Program. Then add this code to enter and verify the phone number.


public class Program {
  public static void Main(string[] args) {
    Console.WriteLine(PhoneNumber.IsPhoneNbr("012.345.6789"));
  }
}

Validate international phone numbers in C#

The code shown above verifies phone numbers with a common format, like 0123456789, 012-345-6789, and (012) -345-6789. However, there will be situations when you will have to consider other formats, the number of digits, and even area codes. For example, telephone numbers in France start with +33. How can you validate the user input?

To perform the verification and a default validation of the phone number field, you have to use Regex in a different pattern:


^([\+]?33[-]?|[0])?[1-9][0-9]{8}$

Let’s use it with the following code to verify this phone number and confirm data type: +33298765432


using System;
using System.Text.RegularExpressions;

public static class PhoneNumber
{
  // Regular expression used to validate a phone number.
  public const string motif = @"^([\+]?33[-]?|[0])?[1-9][0-9]{8}$";

  public static bool IsPhoneNbr(string number)
  {
    if (number != null) return Regex.IsMatch(number, motif);
    else return false;
  }
}

public class Program {
  public static void Main(string[] args) {
    Console.WriteLine(PhoneNumber.IsPhoneNbr("+33298765432"));
  }
}

You will get this output:


True

That means the number is valid. You can apply the same principles to both client side validation and server side validation.

Using .NET Core Data to validate phone numbers

.NET is an open-source platform. It enables you to build cross-platform applications conveniently. It is very popular among developers worldwide.

Applications built with .NET framework are written in C#. The platform supports an open-source library, called libphonenumber-csharp. You can use it to validate phone numbers  the user entered effectively without too many variables.

The libphonenumber-csharp C# library

Google developed an open-source Java, C++, and JavaScript library for validating international phone numbers. It is known as libphonenumber. The library made the life of development teams a lot easier. However, it didn’t benefit the C# developers that much. They didn’t find it convenient for server-side data validation in ASP.NET or ASP.NET Core.

To solve the issue, developer Tom Clegg created a port of libphonenumber to C#, known as libphonenumber-csharp. It enables you to implement Google’s libphonenumber conveniently into your .NET application.

How can you validate phone numbers using libphonenumber-csharp and .NET?

You can perform the verification by following these steps:

Create a New ASP.NET Core MVC Project

First, you have to create a new ASP.NET Core MVC Project. You can name it PhoneCheck. Make sure to choose the Web Application (Model-View-Controller) template.

Include libphonenumber-csharp to Your ASP.NET Core MVC Project

Go to the Package Manager Console window and enter this command:


PM> Install-Package libphonenumber-csharp -Version 8.9.10

Add the ViewModel

Now, you have to create a ViewModel. It will contain fields for the phone number's issuing country. Also, it will have the number to check.

In the Models folder of the project that you have created, you have to add a class file, called PhoneNumberCheckViewModel.cs. Then you have to insert this code:


using System.ComponentModel.DataAnnotations;

namespace PhoneCheck.Models
{
  public class PhoneNumberCheckViewModel
  {
    private string _countryCodeSelected;

    [Required]
    [Display(Name = "Issuing Country")]
    public string CountryCodeSelected
    {
      get => _countryCodeSelected;
      set => _countryCodeSelected = value.ToUpperInvariant();
    }

    [Required]
    [Display(Name = "Number to Check")]
    public string PhoneNumberRaw { get; set; }
    
    // Holds the validation response. Not for data entry.
    [Display(Name = "Valid Number")]
    public bool Valid { get; set; }

    // Holds the validation response. Not for data entry.
    [Display(Name = "Has Extension")]
    public bool HasExtension { get; set; }

    // Optionally, add more fields here for returning data to the user.
  }
}

You can utilize the BlipPhone sample project for populating a dropdown field with a list of countries. It enables you to return a two-character ISO country code in the ViewModel. Alternatively, you can use the CountryCodeSelected field as a plain text field. In this case, you have to enter the country codes manually.

Add the View

Go to the Views folder and create a Phone subfolder. Then you have to create a new view, called Check using the Create template and the PhoneNumberCheckViewModel.cs ViewModel. Once the MVC tooling is done with scaffolding the new view, the Razor markup generated for the PhoneNumberRaw field in the Check.cshtml file will look like this:


...
span asp-validation-for="CountryCodeSelected" class="text-danger" /span
/div
div class="form-group"
  label asp-for="PhoneNumberRaw" class="control-label" /label
  input asp-for="PhoneNumberRaw" class="form-control" /
  span asp-validation-for="PhoneNumberRaw"
class="text-danger" /span
/div
div class="form-group"
  div class="checkbox"
  label
...

Now, you have to edit the view to enable the error messages. In the <form> element, change the first <div> element to this:


div asp-validation-summary="All" class="text-danger" /div

You can view the HTML code for the PhoneNumberRaw field by visiting this URL in the browser: https://localhost:44383/Phone/Check. It will look like this:


...
  span class="text-danger field-validation-valid"
data-valmsg-for="CountryCodeSelected"
data-valmsg-replace="true" /span
/div
div class="form-group"
  label class="control-label" for="PhoneNumberRaw">Number to Check /label
  input class="form-control" type="text" data-val="true"
data-val-required="The Number to Check field is required."
id="PhoneNumberRaw" name="PhoneNumberRaw" value="" /
  span class="text-danger field-validation-valid"
data-valmsg-for="PhoneNumberRaw"
data-valmsg-replace="true" /span /div
div class="form-group"
  div class="checkbox"
  label
...

Now, let’s take a look at the <input> field.


input class="form-control" type="text" data-val="true"
data-val-required="The Number to Check field is required."
id="PhoneNumberRaw" name="PhoneNumberRaw" value="" /

Here, you can see that the <input> field is automatically marked as required. Also, the data validation attributes are connected with it (data-val-required).

Add Controller

You will need to utilize Controller for validating the phone numbers in C# and .NET. Create a new controller in the project’s Controllers folder using the default tooling, called PhoneController.

Then you have to include the PhoneNumber and PhoneCheck.Models namespaces to the PhoneController.cs file.


using PhoneNumbers;
using PhoneCheck.Models;

Next, you have to add a private member variable for the phone number utility class. You need to create an instance of the utility class in the controller constructor.


namespace PhoneCheck.Controllers
{
  public class PhoneController : Controller
  {
    private static PhoneNumberUtil _phoneUtil;

    public PhoneController()
    {
      _phoneUtil = PhoneNumberUtil.GetInstance();
    }
...

Notice that the new instance of PhoneNumberUtil has been created with the GetInstance() method, which results from the libphonenumber-csharp library.

Change the Default Action Name

You have to change the default name of the action, which is Index(), to Check().  


public IActionResult Check()
{
  return View();
}

Add the HttpPost Action Method

The controller action method accepts the view model returned from the HTML form by the MVC middleware. It validates the antiforgery token and the model state of the view model. If the validation is OK, you can use the PhoneNumberUtil instance for validating phone numbers.

For creating HttpPost action, you have to use this code:


[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Check(PhoneNumberCheckViewModel model)
{
  if (model == null)
  {
    throw new ArgumentNullException(nameof(model));
  }
  if (ModelState.IsValid)
    {
    try
      {
        // Parse the number to check into a PhoneNumber object.
        PhoneNumber phoneNumber = _phoneUtil.Parse(model.PhoneNumberRaw,
          model.CountryCodeSelected);
        ModelState.FirstOrDefault(x => x.Key == nameof(model.Valid)).Value.RawValue = _phoneUtil.IsValidNumberForRegion(phoneNumber,
          model.CountryCodeSelected);
        ModelState.FirstOrDefault(x => x.Key == nameof(model.HasExtension)).Value.RawValue = phoneNumber.HasExtension;
          return View(model);
        }
        catch (NumberParseException npex)
        {
          ModelState.AddModelError(npex.ErrorType.ToString(), npex.Message);
        }
      }
      ModelState.SetModelValue(nameof(model.CountryCodeSelected),
        model.CountryCodeSelected, model.CountryCodeSelected);
      ModelState.SetModelValue(nameof(model.PhoneNumberRaw),
        model.PhoneNumberRaw, model.PhoneNumberRaw);

      ModelState.SetModelValue(nameof(model.Valid), false, null);
      model.Valid = false;
      ModelState.SetModelValue(nameof(model.HasExtension), false, null);
      model.HasExtension = false;

      return View(model);
}

That’s it! Now, the project will run. You can validate phone numbers in different formats no matter the area code, like these: 446681800 and 617-229-1234 x1234 (Extension number).

If you get stuck, make sure to check the BlipPhone project file for guidance.

Alternatives for validating phone numbers in C#

You can consider using APIs. They can make the mobile number and phone number validation process incredibly easy. As a result, you can perform the verification quickly and effortlessly.

How about using a lightweight and super-fast API, like Abstract’s Phone Validation API? It can make your life a lot easier. It enables you to validate phone numbers instantly.

Let’s verify this phone number with Abstract’s Phone Validation API: 14154582468


https://phonevalidation.abstractapi.com/v1/
  ? api_key = YOUR_UNIQUE_API_KEY
  & phone = 14154582468

If the given phone number is valid, you will get this response:


{
  "phone": "14154582468",
  "valid": true,
  "local_format":"4154582468",
  "international_format": "+14154582468",
  "country_name": "United States of America",
  "country_code": "US",
  "country_prefix":"+1",
  "registered_location": "San Francisco, CA",
  "carrier":"Verizon USA",
  "line_type": "Mobile",
}

As you can see “valid" is set to true. That means the phone number that you have provided is valid. Also, it returns several key information, like international format, country name, and carrier.

Notice that you are not required to write any code from scratch. You just need to get the API key and the phone number to get the validation instantly. So, Abstract’s Phone Validation API can eliminate complexity while boosting your productivity effectively.

Wrapping Up

That’s it! You have learned the way of validating phone numbers using C#. You can utilize Regex and libphonenumber-csharp to get the job done. However, the easiest way is using Abstract’s Phone Validation API. It can help you to verify the phone number instantly and effortlessly.

4.6/5 stars (14 votes)

Emma Jagger
Engineer, maker, Google alumna, CMU grad
Get your free
Phone Validation API
API
key now
Validate phone numbers instantly using Abstract's phone verification API.
get started for free

Related Articles

Get your free
API
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required