Ensuring phone numbers are valid is a key step in C# development for maintaining data integrity. We will explore five different methods for phone number validation, complete with working code snippets. We'll also examine the common pitfalls of these approaches and see how Abstract API addresses these issues.
How to Implement Phone Number Validation in C#
Here are four distinct methods to validate phone numbers in your C# applications. Each approach comes with a detailed explanation and a functional code snippet for implementation.
Validation with a Regular Expression
A raw regex offers the quickest way to block malformed input when you know the accepted formats. A single line of code can be placed anywhere, such as in a controller or a value-object factory. The "compiled" flag makes its run-time performance cost negligible after the first match.
You can extend this method through a chain of multiple patterns or with a switch on the detected country. The code below shows an example for an Australian phone number.
string pattern = @"^([\+]?61[-]?|0)?[1-9][0-9]{8}$"; // AU example
bool ok = Regex.IsMatch(input, pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant);
Validation with System.ComponentModel.DataAnnotations
The model-binding pipeline in ASP.NET Core can reject incorrect numbers in a declarative way. You can use attributes like the "[Phone]" attribute for a coarse sanity check. For stricter validation, you can combine it with a "[RegularExpression]" attribute or a custom "ValidationAttribute".
The MVC filter executes these attributes automatically. This means no special code is necessary inside controllers or APIs to trigger the validation logic.
public sealed class Customer
{
[Required]
[Phone] // coarse sanity check
[RegularExpression(@"^\+?[1-9]\d{1,14}$")] // E.164 override
public string Phone { get; init; }
}
Validation with libphonenumber-csharp
This method requires the addition of the libphonenumber-csharp NuGet package to your project. The library possesses knowledge of national and international formats for more than 200 regions. It can also normalize numbers, detect the number type, and format the number as a user types.
The core of the validation logic involves the "PhoneNumberUtil" class. You first parse the raw string with a region code. Then, you check if the parsed number is valid. The parse operation throws an exception on syntax errors.
using PhoneNumbers;
static bool IsValid(string raw, string region)
{
var util = PhoneNumberUtil.GetInstance();
var parsed = util.Parse(raw, region); // throws on syntax errors
return util.IsValidNumber(parsed); // structural + metadata checks
}
Validation with GlobalPhone
GlobalPhone is a lighter wrapper with a simpler API. The API returns null on bad input, which gives you a one-liner that will not throw an exception unless you explicitly ask it to. This makes it a good choice when you only need to confirm validity or normalize a number.
using GlobalPhone;
var n = GlobalPhone.Parse("+1-312-555-1212");
bool ok = n?.IsValid ?? false;
string e164 = n?.InternationalString;
Challenges of Phone Number Validation in C#
The methods discussed present their own set of trade-offs. These approaches often fall short in real-world scenarios due to several persistent issues with phone number data and formats.
- Numbering plans change constantly with new prefixes and shifting area codes. This makes any regular expression or custom rule set outdated almost as soon as it is deployed, which leads to validation failures.
- The [Phone] attribute in System.ComponentModel.DataAnnotations only confirms the presence of phone-like characters. It ignores country context, length limits, and reserved number ranges, which results in both false positives and missed errors.
- Libraries like libphonenumber-csharp and GlobalPhone rely on static metadata. This data lags behind official updates from regulators and cannot confirm if a number is currently assigned or ported, so a structurally valid number may not be reachable.
- User input is often ambiguous. People paste local numbers with trunk zeros, vanity text, or extensions. This makes it difficult to reliably convert a number into a standard format like E.164 for consistent validation.
Validate Phone Numbers with Abstract API
Implement phone number validation in C# to ensure data integrity and improve user communication.
Get started for free
How Abstract API Handles Phone Number Validation in C#
Abstract API addresses the core weaknesses of traditional methods through a single API call that returns comprehensive, real-time data.
- It eliminates manual rule upkeep because it relies on continuously updated telecom and numbering data, a significant improvement over brittle regex rules or static libraries.
- The API confirms if a number is live and identifies its carrier and line type. This function lets you block high-risk numbers, such as VoIP or premium lines, in real time.
- You receive predictable latency, forward-compatible upgrades, and SOC 2/GDPR-compliant data processes without any infrastructure to maintain.
How to Bring Abstract API to Your Dev Environment
Once you are familiar with Abstract’s capabilities, the addition of its phone number validation API to your project is simple.
- First, sign up at Abstract and generate a Phone Validation API key.
- Create or open a .NET 6+ project.
- Add the System.Net.Http.Json package via the command `dotnet add package System.Net.Http.Json`.
- Store your API key in a secure configuration, like Secrets Manager or an environment variable.
- Register a typed HttpClient and set its BaseAddress to `https://phonevalidation.abstractapi.com/v1/`.
- Inject the client, make the call, and parse the JSON response.
Sample Phone Number Validation Implementation with Abstract API
The C# code below demonstrates a basic implementation. It defines records to match the structure of the API's JSON response. The code retrieves an API key from environment variables, specifies the phone number to validate, and creates an HttpClient instance pointed at the Abstract API endpoint. It then constructs the request URI and performs an asynchronous GET request, which deserializes the JSON response into the `PhoneResponse` record. Finally, it checks if the number is valid and has a "mobile" type before it prints a confirmation message.
record PhoneResponse(string phone, bool valid, Format format,
Country country, string location,
string type, string carrier);
record Format(string international, string local);
record Country(string code, string name, string prefix);
var key = Environment.GetEnvironmentVariable("ABSTRACT_KEY");
var number = "14152007986";
using var client = new HttpClient { BaseAddress = new Uri("https://phonevalidation.abstractapi.com/v1/") };
var uri = $"?api_key={key}&phone={number}";
var data = await client.GetFromJsonAsync<PhoneResponse>(uri);
if (data?.valid == true && data.type == "mobile")
{
Console.WriteLine($"User number {data.format.international} is good – {data.carrier} in {data.location}");
}
The API returns a detailed JSON object that contains all the necessary validation data.
{
"phone": "14152007986",
"valid": true,
"format": {
"international": "+14152007986",
"local": "(415) 200-7986"
},
"country": {
"code": "US",
"name": "United States",
"prefix": "+1"
},
"location": "California",
"type": "mobile",
"carrier": "T-Mobile USA, Inc."
}
Each field provides a specific piece of information. The "valid" field confirms the number is reachable, while "format" supplies normalized local and international versions. The "country" and "location" fields enable geo-based rules, and "type" lets you block unwanted lines like VoIP. The "carrier" data can support downstream provider selections.
Final Thoughts
Traditional methods like regex often fail because they only check format and cannot adapt to new country rules. Static libraries are an improvement but cannot confirm if a number is live. Abstract API overcomes these issues with real-time data that confirms validity, line type, and carrier. To reliably validate user phone numbers, create an account on Abstract API and get your free API key.
Validate Phone Numbers with Abstract API
Validate phone numbers in your C# application to maintain clean data and reliable user contact.
Get started for free