Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Mobile number to international format in C#

Tags:

c#

asp.net

I have to convert mobile number to International format.

ex: if user enters the number in below format:

0274 123 4567(Newzeland)
09916123764(India)

Conversion should happen

+642741234567 (Newzeland)
+919916123764 (India)

Tried with lots of regular expressions, but just these are validating, but replace is not happening.

Found some similar link in Stack overflow, but it's in Python.

Formatting a mobile number to international format

For normal mobile validation i am using below code.

protected bool IsValidPhone(string strPhoneInput)
{
    // Remove symbols (dash, space and parentheses, etc.)
    string strPhone = Regex.Replace(strPhoneInput, @"[- ()\*\!]", String.Empty);

    // Check for exactly 10 numbers left over
    Regex regTenDigits = new Regex(@"^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$");
    Match matTenDigits = regTenDigits.Match(strPhone);

    return matTenDigits.Success;
}

Could any body tell us how to convert this into C#.

like image 974
Chiranjeevi Avatar asked Dec 11 '22 23:12

Chiranjeevi


2 Answers

For posterity's sake, here is a c# port of Google's LibPhoneNumber (official repository). The library provides a variety of methods for validating and formatting phone numbers.

https://www.nuget.org/packages/libphonenumber-csharp/

An example with this library.

string localPhoneNumber = "(555) 555-5555"
PhoneNumber pn = PhoneNumberUtil.Instance.Parse(localPhoneNumber, "US");
string internationalPhoneNumber = pn.Format(PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
//result +1-555-555-5555
like image 131
farlee2121 Avatar answered Feb 08 '23 23:02

farlee2121


farlee2121's answer is deprecated. Now when using the libphonenumber-csharp package your task should be done this way:

string phoneNumber = Console.ReadLine();
PhoneNumber pn = PhoneNumberUtil.GetInstance().Parse(phoneNumber, "US");
string internationalPhoneNumber = PhoneNumberUtil.GetInstance().Format(pn, PhoneNumberFormat.INTERNATIONAL);
like image 27
Anthony Minchenko Avatar answered Feb 09 '23 00:02

Anthony Minchenko