// The metadata needed by this class is the same for all regions sharing the same country calling // code. Therefore, we return the metadata for "main" region for this country calling code. private PhoneMetadata GetMetadataForRegion(string regionCode) { var countryCallingCode = phoneUtil.GetCountryCodeForRegion(regionCode); var mainCountry = phoneUtil.GetRegionCodeForCountryCode(countryCallingCode); var metadata = phoneUtil.GetMetadataForRegion(mainCountry); return(metadata ?? EmptyMetadata); // Set to a default instance of the metadata. This allows us to function with an incorrect // region code, even if formatting only works for numbers specified with "+". }
// The metadata needed by this class is the same for all regions sharing the same country calling // code. Therefore, we return the metadata for "main" region for this country calling code. private PhoneMetadata GetMetadataForRegion(String regionCode) { int countryCallingCode = phoneUtil.GetCountryCodeForRegion(regionCode); String mainCountry = phoneUtil.GetRegionCodeForCountryCode(countryCallingCode); PhoneMetadata metadata = phoneUtil.GetMetadataForRegion(mainCountry); if (metadata != null) { return(metadata); } // Set to a default instance of the metadata. This allows us to function with an incorrect // region code, even if formatting only works for numbers specified with "+". return(EMPTY_METADATA); }
public static string formatE164(string countryCode, string number) { if (countryCode == string.Empty || number == string.Empty) { return(string.Empty); } try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); int parsedCountryCode = Convert.ToInt32(countryCode); PhoneNumber parsedNumber = util.Parse(number, util.GetRegionCodeForCountryCode(parsedCountryCode)); return(util.Format(parsedNumber, PhoneNumberFormat.E164)); } catch (NumberParseException npe) { return(string.Empty); } catch (Exception npe) { return(string.Empty); } return("+" + countryCode.ReplaceAll("[^0-9]", "").ReplaceAll("^0*", "") + number.ReplaceAll("[^0-9]", "")); }
/// <summary> /// Attempts to normalized the given phone number for the given region code. /// </summary> /// <param name="phoneNumber">The phone number to normalize.</param> /// <param name="regionCode"> /// Region that we are expecting the number to be from. /// This is only used if the number being parsed is not written in international format. /// </param> /// <param name="normalized">The normalized string or the original string if normalization failed.</param> /// <returns>True if normalization succeeds, otherwise false.</returns> public static bool TryNormalizeRc(string phoneNumber, string regionCode, out string normalized) { EnsurePhoneUtil(); EnsureRegionTimezoneMap(); normalized = phoneNumber; if (String.IsNullOrWhiteSpace(phoneNumber)) { return(false); } phoneNumber = phoneNumber .Trim() .Replace("o", "0") .Replace("O", "0"); try { var parsedNumber = _phoneUtil.Parse(phoneNumber, regionCode); if (_phoneUtil.IsValidNumber(parsedNumber)) { normalized = $"+{parsedNumber.CountryCode}{parsedNumber.NationalNumber}"; return(true); } // Check the case where country code is included without the + or 00 prefix // as libphone wont recoginize as country code unless we add one of the above // prefixes. else if (phoneNumber.Length >= 10 && Regex.IsMatch(phoneNumber, @"^\d")) { foreach (var countryCode in _phoneUtil.GetSupportedCallingCodes()) { var region = _phoneUtil.GetRegionCodeForCountryCode(countryCode); var exampleNumber = _phoneUtil.GetExampleNumberForType(region, PhoneNumberType.MOBILE).NationalNumber; var sCountryCode = countryCode.ToString(); var totalLength = sCountryCode.Length + exampleNumber.ToString().Length; if (phoneNumber.StartsWith(sCountryCode) && phoneNumber.Length == totalLength) { return(TryNormalizeRc($"+{phoneNumber}", regionCode, out normalized)); } } } else { return(false); } } catch { return(false); } return(false); }
public static bool IsNationalPrefixPresentIfRequired(PhoneNumber number, PhoneNumberUtil util) { // First, check how we deduced the country code. If it was written in international format, then // the national prefix is not required. if (number.CountryCodeSource != PhoneNumber.Types.CountryCodeSource.FROM_DEFAULT_COUNTRY) { return(true); } String phoneNumberRegion = util.GetRegionCodeForCountryCode(number.CountryCode); PhoneMetadata metadata = util.GetMetadataForRegion(phoneNumberRegion); if (metadata == null) { return(true); } // Check if a national prefix should be present when formatting this number. String nationalNumber = util.GetNationalSignificantNumber(number); NumberFormat formatRule = util.ChooseFormattingPatternForNumber(metadata.NumberFormatList, nationalNumber); // To do this, we check that a national prefix formatting rule was present and that it wasn't // just the first-group symbol ($1) with punctuation. if ((formatRule != null) && formatRule.NationalPrefixFormattingRule.Length > 0) { if (formatRule.NationalPrefixOptionalWhenFormatting) { // The national-prefix is optional in these cases, so we don't need to check if it was // present. return(true); } // Remove the first-group symbol. String candidateNationalPrefixRule = formatRule.NationalPrefixFormattingRule; // We assume that the first-group symbol will never be _before_ the national prefix. candidateNationalPrefixRule = candidateNationalPrefixRule.Substring(0, candidateNationalPrefixRule.IndexOf("${1}")); candidateNationalPrefixRule = PhoneNumberUtil.NormalizeDigitsOnly(candidateNationalPrefixRule); if (candidateNationalPrefixRule.Length == 0) { // National Prefix not needed for this number. return(true); } // Normalize the remainder. String rawInputCopy = PhoneNumberUtil.NormalizeDigitsOnly(number.RawInput); StringBuilder rawInput = new StringBuilder(rawInputCopy); // Check if we found a national prefix and/or carrier code at the start of the raw input, and // return the result. return(util.MaybeStripNationalPrefixAndCarrierCode(rawInput, metadata, null)); } return(true); }
public async void ValidatePhoneHtmlAsync() { wbBrowser.DocumentText = "<html></html>";//Directly setting HTML content for first time doesnt work. StringBuilder htmlContent = new StringBuilder("<H3><CENTER>OPEN SOURCE PHONE VALIDATION<CENTER></H3>"); htmlContent.Append("<hr/>"); string countryCode = cbCountry.SelectedValue.ToString(); string typedPhoneNumber = txtPhoneInput.Text; if (typedPhoneNumber.Length >= 1 && countryCode.Length >= 1) { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumber phonenumberObject = null; //await Task.Run(() => { phonenumberObject = phoneUtil.Parse(typedPhoneNumber, countryCode); string regionCoundFromPhoneNumber = phoneUtil.GetRegionCodeForCountryCode(phonenumberObject.CountryCode); htmlContent.Append("<table border=\"0\" cellpadding=\"1\" cellspacing=\"0\" style=\"font-family:verdana;font-size:12px;border-colapse:none\" width=\"100%\">"); htmlContent.Append($"<tr><td>Typed Phone Number</td><td>{typedPhoneNumber}</td></tr>"); htmlContent.Append($"<tr><td>Is Valid Phone Number</td><td>{regionCoundFromPhoneNumber == countryCode && phoneUtil.IsValidNumber(phonenumberObject)}</td></tr>"); PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.GetInstance(); if (regionCoundFromPhoneNumber == countryCode && phoneUtil.IsValidNumber(phonenumberObject)) { htmlContent.Append($"<tr><td>Country Code</td><td>{Convert.ToString(phonenumberObject.CountryCode)}</td></tr>"); htmlContent.Append($"<tr><td>E164 Format </td><td>{phoneUtil.Format(phonenumberObject, PhoneNumberFormat.E164) }</td></tr>"); htmlContent.Append($"<tr><td>Intenational Format</td><td>{phoneUtil.Format(phonenumberObject, PhoneNumberFormat.INTERNATIONAL)}</td></tr>"); htmlContent.Append($"<tr><td>RFC Format </td><td>{phoneUtil.Format(phonenumberObject, PhoneNumberFormat.RFC3966) }</td></tr>"); htmlContent.Append($"<tr><td>National Format</td><td>{phoneUtil.Format(phonenumberObject, PhoneNumberFormat.NATIONAL)}</td></tr>"); htmlContent.Append($"<tr><td>Has CountryCode </td><td>{ Convert.ToString(phonenumberObject.HasCountryCode)}</td></tr>"); htmlContent.Append($"<tr><td>Phone Number Type </td><td>{ phoneUtil.GetNumberType(phonenumberObject)}</td></tr>"); htmlContent.Append($"<tr><td>Phone Location </td><td>{geocoder.GetDescriptionForNumber(phonenumberObject, Locale.ENGLISH)}</td></tr>"); htmlContent.Append("</table>"); WriteToHtmlControl(htmlContent.ToString()); //PhoneNumberEnrichInformaticaHtml(htmlContent, phoneUtil.Format(phonenumberObject, PhoneNumberFormat.E164)); } else { htmlContent.Append("</table>"); WriteToHtmlControl(htmlContent.ToString()); } } catch (NumberParseException ex) { MessageBox.Show("Invalid Phone Number"); } } }
private PhoneNumber BuildPhoneNumber(string number) { PhoneNumber result = null; var sanitized = RecipientHelper.GetSanitizedMobileNumber(number); int countryCode = RecipientHelper.GetCountryCodeFromMobile(number); var regionCode = _util.GetRegionCodeForCountryCode(countryCode); try { result = _util.Parse(sanitized, regionCode); } catch { return(null); } return(result); }
public static string FormatE164(string countryCode, string number) { if (countryCode == string.Empty || number == string.Empty) { return(string.Empty); } try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); int parsedCountryCode = Convert.ToInt32(countryCode); PhoneNumber parsedNumber = util.Parse(number, util.GetRegionCodeForCountryCode(parsedCountryCode)); return(util.Format(parsedNumber, PhoneNumberFormat.E164)); } catch (Exception e) { Logger.LogError("FormatNumber() failed: {0}\n{1}", e.Message, e.StackTrace); } return("+" + countryCode.ReplaceAll("[^0-9]", "").ReplaceAll("^0*", "") + number.ReplaceAll("[^0-9]", "")); }