Phone number validation is a standard step for maintaining data integrity in C# applications. Five distinct methods, complete with code snippets, can handle this task. The discussion also covers the pitfalls of these traditional techniques and shows how Abstract API solves these common problems.
How to Validate Phone Numbers in C#
C# offers several ways to check phone numbers for correctness. These methods range from simple pattern matches to comprehensive library functions that handle complex international and regional rules.
Regular Expression
A raw regular expression, or regex, provides a fast way to block malformed input when you know the accepted format. A single line of code can be injected anywhere in your application. The compiled flag makes it negligible at run time after the first match. You can extend this method with a chain of multiple patterns or use a switch on the detected country.
string pattern = @"^([\+]?61[-]?|0)?[1-9][0-9]{8}$"; // AU example
bool ok = Regex.IsMatch(input, pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant);
System.ComponentModel.DataAnnotations
ASP.NET Core’s model-binding pipeline can reject bad numbers declaratively. The MVC filter executes the attributes automatically, so no special code is needed in controllers or APIs. You can combine the `[Phone]` attribute, which offers a coarse sanity check, with a stricter `[RegularExpression]` or a custom ValidationAttribute when regional rules matter.
public sealed class Customer
{
[Required]
[Phone] // coarse sanity check
[RegularExpression(@"^\+?[1-9]\d{1,14}$")] // E.164 override
public string Phone { get; init; }
}
libphonenumber-csharp
This method uses a NuGet package ported from Google's library. It is important to keep the package updated, as the metadata behind the `IsValidNumber` function changes frequently. The library knows national and international formats for over 200 regions. It also normalizes numbers and detects their type, such as mobile or toll-free.
The code uses the `PhoneNumberUtil` class to parse and validate the number. The `Parse` method throws an exception on syntax errors, while `IsValidNumber` performs structural and metadata checks.
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
}
GlobalPhone
GlobalPhone is a lighter wrapper around the same metadata as libphonenumber but with a simpler API. The `Parse` method returns null on bad input. This approach allows for a one-liner check that will not throw an exception.
It is a good choice when you only need to validate or normalize a number without the full `PhoneNumberUtil` surface.
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#
Traditional validation methods in C# present several obstacles. These techniques often struggle with the dynamic nature of global phone networks, which leads to unreliable results and maintenance overhead for developers.
- Numbering plans constantly change with new prefixes and variable lengths. This reality makes any custom
Regular Expression
outdated almost as soon as it is deployed. Maintenance becomes a continuous and difficult task for developers to manage. - The
System.ComponentModel.DataAnnotations.PhoneAttribute
only confirms phone-like characters. It ignores country context, length limits, and reserved number ranges. This superficial check leads to both false positives and missed errors in a production environment. - Libraries like
libphonenumber-csharp
and GlobalPhone
rely on static metadata. Since regulators publish updates with a delay, the data can be stale. A structurally valid number does not guarantee it is assigned or reachable. - User input formats are ambiguous and inconsistent. People submit local numbers with trunk zeros, vanity text, or extensions. This variety makes it difficult to normalize a number into a single, reliable canonical string like E.164.
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 validation methods with a single API call that provides real-time data.
- A single HTTPS GET call returns validity, international and local formats, carrier, line type, country, and region. The response uses continuously-updated telecom and number plan data, which removes the need for manual rule updates.
- The system eliminates false positives on disconnected or disposable numbers. It also lets you gate high-risk line types, such as VoIP or premium numbers, in real time.
- The API is stateless, CDN-backed, and versioned. This design gives you predictable latency, forward-compatible upgrades, and SOC 2 / GDPR compliance without infrastructure to maintain.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you can add its phone number validation API to your project with ease. The process involves a few straightforward steps to prepare your C# environment.
- First, sign up at Abstract and generate a Phone Validation API key.
- Create or open a .NET 6+ project. This can be a web, worker, or console application.
- Add the necessary package to your project. For example, you can use the .NET CLI for this.
- Store your API key in a secure location, like the Secrets Manager or as an environment variable.
- Register a typed HttpClient and set its BaseAddress to the Abstract API endpoint.
- Finally, inject the client, construct the API call, and parse the JSON response.
To add the required package, execute the following command in your terminal:
dotnet add package System.Net.Http.Json
Sample Phone Number Validation Implementation with Abstract API
The C# code below shows a minimal implementation. It defines data records that map to the API's JSON response structure. The code then retrieves an API key and a sample phone number, and uses an HttpClient to send a GET request to the API endpoint.
After the call, it checks if the response marks the number as valid and confirms the line type is "mobile." If both conditions are true, it prints a formatted string with the carrier and location details to the console.
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}");
}
A successful request returns a detailed JSON object. This object contains all the validation information you need.
{
"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."
}
The `valid` field confirms the number is active and reachable. The `format` object provides both international and local versions for consistent display or storage. The `country`, `location`, and `prefix` fields allow for geo-based logic or fraud detection rules.
You can use the `type` field to block specific line types like VoIP or premium numbers. The `carrier` information supports downstream tasks, such as the selection of an SMS or voice provider.
Final Thoughts
Traditional validation methods are often brittle and rely on static data that requires manual updates. Abstract API overcomes these issues with a single, real-time API call that provides comprehensive and accurate data. To reliably validate phone numbers, consider an account on Abstract API to 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