Skip to content

Instantly share code, notes, and snippets.

@fravelgue
Created October 26, 2020 15:48
Show Gist options
  • Save fravelgue/5f7f2ee441854ef15c0e2b7b14be0e0d to your computer and use it in GitHub Desktop.
Save fravelgue/5f7f2ee441854ef15c0e2b7b14be0e0d to your computer and use it in GitHub Desktop.
PhoneNumber Extension Methods (libphonenumber)
//https://github.com/erezak/libphonenumber-csharp
//https://github.com/twcclegg/libphonenumber-csharp
using PhoneNumbers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace fravelgue
{
public static class PhoneNumberExtensions
{
public static bool IsValid(this PhoneNumberUtil util, string phone, string country, out PhoneNumber pn)
{
bool isValid = false;
try
{
pn = util.Parse(phone, country.ToUpperInvariant());
}
catch (NumberParseException)
{
pn = null;
}
if (pn != null && util.IsValidNumber(pn))
{
isValid = true;
}
else
{
pn = null;
}
return isValid;
}
public static string ToPhone(this PhoneNumber pn)
{
//return util.Format(pn, PhoneNumberFormat.E164).Replace("+", "").Substring(pn.CountryCode.ToString().Length);
return pn.NationalNumber.ToString();
}
public static string ToMsisdn(this PhoneNumber pn)
{
return pn.CountryCode.ToString() + pn.NationalNumber.ToString();
}
public static string ToMsisdn(this PhoneNumberUtil util, PhoneNumber ph)
{
return util.Format(ph, PhoneNumberFormat.E164).Replace("+", "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment