Koreki Xeri Koreki Xeri - 1 month ago 13
C# Question

Use libphonenumber to validate mobile phone number without knowing the country

I have a list (string) of phone numbers from any country.

for example:

var items = new List<string> { "+989302794433", "009891234599882", "+391234567890", "00336615551212"};



at first, I think that every country code length is exactly two number, for example(33: France, 39: Italy, 98: Iran , ...).



using libphonenumber library, you must be pass the regCode for parsing. and because of (in my scenario) I get the list of string(mobile number), then I must be separate country code from number.

foreach (var item in items)
{
int countryCode = 0;
var number = "";

if (item.StartsWith("+"))
{
countryCode = int.Parse(item.Substring(1, 2));
number = item.Substring(3);
}
else if (item.StartsWith("00"))
{
countryCode = int.Parse(item.Substring(2, 2));
number = item.Substring(4);
}
var regCode = phoneUtil.GetRegionCodeForCountryCode(countryCode);

var numberWithRegCode = phoneUtil.Parse(number, regCode);

if (!phoneUtil.IsValidNumber(numberWithRegCode)) continue;
//else ...
}


this code fine worked just for country codes that their length is two numbers!

but after a little time , I knew that some country code length is one number( for example, US: 1) and even three number!.

now, is exists any way using libphonenumber library (or other solutions) to solve this issue?

thanks a lot

Answer

The libphonenumber library can find country codes by itself as long as the number starts with a +. So, just replace double zeros at the beginning of a number with a plus. And then let the library decide whether the number is valid on its own.

libphonenumber will on its own know which is the country code following the plus sign (it internally has a list of all the codes) and then apply the rules according to the correct country to decide whether the number is valid.

bool IsValidNumber(string aNumber)
{
    bool result = false;

    aNumber = aNumber.Trim();

    if (aNumber.StartsWith("00"))
    {
        // Replace 00 at beginning with +
        aNumber = "+" + aNumber.Remove(0, 2);
    }

    try
    {
        result = PhoneNumberUtil.Instance.Parse(aNumber, "").IsValidNumber;
    }
    catch
    {
        // Exception means is no valid number
    }

    return result; 
}