Reputation: 171
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#.
Upvotes: 7
Views: 15192
Reputation: 461
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);
Upvotes: 10
Reputation: 3337
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
Upvotes: 13
Reputation: 171
Thanks for the suggestions, i will check with service team regarding country codes. but just for stub creation i used the below code which is manageable.
private string IsMobileNumberValid(string mobileNumber) {
// remove all non-numeric characters
string _mobileNumber = CleanNumber(mobileNumber);
// trim any leading zeros
_mobileNumber = _mobileNumber.TrimStart(new char[] { '0' });
// check for this in case they've entered 44 (0)xxxxxxxxx or similar
if (_mobileNumber.StartsWith("+640"))
{
_mobileNumber = _mobileNumber.Remove(2, 1);
}
// add country code if they haven't entered it
//If we need to handle with multiple Country codes we have to place a list here,Currently added +64 as per document.
if (!_mobileNumber.StartsWith("+64"))
{
_mobileNumber = "+64" + _mobileNumber;
}
// check if it's the right length
if (_mobileNumber.Length != 12)
{
return _mobileNumber;
}
return _mobileNumber;
}
public string CleanNumber(string phone)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(phone, "");
}
Upvotes: -2