How to validate a Phone Number in C# .NET Framework
1 min readJul 15, 2020
Phone number validation is a tricky thing to set up in C#, requiring you to account for many possible phone number formats, international numbers, and other hidden pitfalls. Rather than depart down that tedious road, we will instead be using an API to get the job done for us, and in record time!
For our API, we will need its client library:
Install-Package Cloudmersive.APIClient.NET.Validate -Version 3.0.6
Next step, calling our function:
using System;using System.Diagnostics;using Cloudmersive.APIClient.NET.Validate.Api;using Cloudmersive.APIClient.NET.Validate.Client;using Cloudmersive.APIClient.NET.Validate.Model;namespace Example{public class PhoneNumberSyntaxOnlyExample{public void main(){// Configure API key authorization: ApikeyConfiguration.Default.AddApiKey("Apikey", "YOUR_API_KEY");// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new PhoneNumberApi();var value = new PhoneNumberValidateRequest(); // PhoneNumberValidateRequest | Phone number to validate in a PhoneNumberValidateRequest object. Try a phone number such as \"1.800.463.3339\", and either leave DefaultCountryCode blank or use \"US\".try{// Validate phone number (basic)PhoneNumberValidationResponse result = apiInstance.PhoneNumberSyntaxOnly(value);Debug.WriteLine(result);}catch (Exception e){Debug.Print("Exception when calling PhoneNumberApi.PhoneNumberSyntaxOnly: " + e.Message );}}}}
And that’s all there is to it!