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#.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With