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:
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.
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.
3. Create a new class, called Program. Then add this code to enter and verify the phone number.
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:
Let’s use it with the following code to verify this phone number and confirm data type: +33298765432
You will get this output:
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:
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:
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:
Now, you have to edit the view to enable the error messages. In the <form> element, change the first <div> element to this:
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:
Now, let’s take a look at the <input> field.
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.
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.
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().
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:
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
If the given phone number is valid, you will get this response:
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.