Validating phone numbers with libphonenumber library in C# Options

codeling 1247 - 5334
@2020-01-07 10:06:06

Google developed and helps maintain an open source Java, C++, and JavaScript library for "parsing, formatting, and validating international phone numbers", libphonenumber.

To facilitate .NET developers to validate phone number in C#, Tom Clegg has created a port of libphonenumber to C#, libphonenumber-csharp. It's available as a NuGet package, which makes it easy to add to any project.

 


codeling 1247 - 5334
@2020-01-07 10:19:54

Install libphonenumber-csharp

You can install it throught Visual Studio by right cliking on the project and choosing Manage Nuget pakcages...search phonenumber:

 

Or you can enter the following command in a Package Manager Console window, substituting the current version information as appropriate:

PM> Install-Package libphonenumber-csharp -Version 8.11.1

Or enter the following .NET command line in a PowerShell window. Be sure the current directory is the project directory:

dotnet add package libphonenumber-csharp --version 8.11.1

codeling 1247 - 5334
@2020-01-07 10:34:09

The following example shows you how to use libphonenumber to validate a phone number in Canada:

using PhoneNumbers;

string inputPhoneNumber = "519888888";
string resultPhoneNumber;

PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
try
{
    PhoneNumber queryPhoneNumber = phoneUtil.Parse(inputPhoneNumber, "CA");
    if (phoneUtil.IsValidNumber(queryPhoneNumber))
    {
        resultPhoneNumber = queryPhoneNumber.NationalNumber.ToString();
    }
                
}
catch
{
    resultPhoneNumber = string.Empty;
}
Users browsing this topic
Guest