//------------------------------------------------------------------------------------------------------------------------- /// <summary> /// Returns the supplied phone number formatted for display purposes. Phone numbers in the +1 country code are returned /// in AAA-PPP-NNNN format. International phone numbers are returned in an industry-standard format including the /// country code. /// </summary> /// <param name="pstn">Phone number to format for display purposes.</param> /// <returns>Phone number formatted for display purposes, or null if the phone number is invalid.</returns> public static string DisplayFormat(string pstn) { if (pstn == null) { return(null); } pstn = pstn.Trim(); if (PhoneNumberUtil.IsPossibleNumber(pstn, "US") == false) { return(null); } PhoneNumbers.PhoneNumber phoneNumber = PhoneNumberUtil.Parse(pstn, "US"); if (phoneNumber.CountryCode == 1) { return(PhoneNumberUtil.Format(PhoneNumberUtil.Parse(pstn, "US"), PhoneNumberFormat.NATIONAL).Replace("(", "").Replace(") ", "-")); } else { return(PhoneNumberUtil.Format(PhoneNumberUtil.Parse(pstn, "US"), PhoneNumberFormat.INTERNATIONAL)); } }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var model = (Register)validationContext.ObjectInstance; if (model == null || String.IsNullOrEmpty(model.PhoneNumber)) { return(new ValidationResult(ErrorMessage)); } if (model == null || String.IsNullOrEmpty(model.Country)) { return(new ValidationResult("Please provide a valid country")); } //phone nnumber formating addopted from //https://stackoverflow.com/questions/30434836/how-to-convert-mobile-number-to-international-format-in-c-sharp Country country = Countries.GetCountry(model.Country); var util = PhoneNumberUtil.GetInstance(); PhoneNumbers.PhoneNumber pn = util.Parse(model.PhoneNumber, country.ShortName.ToUpper()); if (util.IsValidNumberForRegion(pn, country.Code.ToLower())) { return(ValidationResult.Success); } return(new ValidationResult(ErrorMessage + " For the country " + model.Country)); }
public PhoneNumberMatch(int start, String rawString, PhoneNumber number) { if (start < 0) throw new ArgumentException("Start index must be >= 0."); if (rawString == null || number == null) throw new ArgumentNullException(); Start = start; RawString = rawString; Number = number; }
public async Task <bool> IsValidPhoneNumber(string Mobilenumber, string CountryCode) { try { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); //string countryCode = "IN"; //string Code = GetCountryByIP(IpAddress); PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse(Mobilenumber, CountryCode); return(phoneUtil.IsValidNumber(phoneNumber)); // returns true for valid number } catch (Exception ex) { return(false); } }
public async Task <IActionResult> SignUp(UserViewModel userViewModel) { if (ModelState.IsValid) { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); string telephoneNumber = userViewModel.PhoneNumber; string countryCode = "TR"; PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse(telephoneNumber, countryCode); bool isValidRegion = phoneUtil.IsValidNumberForRegion(phoneNumber, countryCode); if (!isValidRegion) { ModelState.AddModelError("", "Geçerli telefon numarası giriniz"); return(View(userViewModel)); } AppUser user = new AppUser() { UserName = userViewModel.UserName, Email = userViewModel.Email, PhoneNumber = userViewModel.PhoneNumber }; IdentityResult result = await userManager.CreateAsync(user, userViewModel.Password); if (result.Succeeded) { string emailConfirmationToken = await userManager.GenerateEmailConfirmationTokenAsync(user); string confirmationLink = Url.Action("ConfirmEmail", "Home", new { userId = user.Id, token = emailConfirmationToken }, protocol: HttpContext.Request.Scheme); EmailConfirmation.SendEmailWithSendGrid(confirmationLink, user.Email).Wait(); return(RedirectToAction("Login")); } else { AddErrorsToModelState(result); } } return(View(userViewModel)); }
public ActionResult SendMessage([Bind("ReservationId, AreaCode, PhoneNumberRaw")] PhoneNumberCheckViewModel phone) { if (ModelState.IsValid) { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { string telephoneNumber = phone.PhoneNumberRaw; string countryCode = phone.AreaCode; PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse("+" + countryCode + telephoneNumber, ""); bool isValidNumber = phoneUtil.IsValidNumber(phoneNumber); // returns true for valid number if (isValidNumber) { var accountSid = EnvironmentVariables.TWILIO_ACCOUNT_SID; var authToken = EnvironmentVariables.TWILIO_AUTH_TOKEN; TwilioClient.Init(accountSid, authToken); Reservation reservation = _db.Reservations.Include(res => res.Event).FirstOrDefault(res => res.ReservationId == Int32.Parse(phone.ReservationId)); string textMessage = $"Your reservation at {reservation.Event.EventTitle} is confirmed!"; var message = MessageResource.Create( from: new Twilio.Types.PhoneNumber(EnvironmentVariables.TWILIO_NUMBER), body: textMessage, to: new Twilio.Types.PhoneNumber(phone.PhoneNumberRaw) ); return(RedirectToAction("Details", new { id = phone.ReservationId })); } ViewBag.Message = "The phone number do not exist."; } catch (NumberParseException ex) { String errorMessage = "NumberParseException was thrown: " + ex.Message.ToString(); } } ViewBag.ReservationId = phone.ReservationId; return(View(phone)); }
/** * Formats a phone number using the original phone number format that the number is parsed from. * The original format is embedded in the country_code_source field of the PhoneNumber object * passed in. If such information is missing, the number will be formatted into the NATIONAL * format by default. When the number contains a leading zero and this is unexpected for this * country, or we don't have a formatting pattern for the number, the method returns the raw input * when it is available. * * Note this method guarantees no digit will be inserted, removed or modified as a result of * formatting. * * @param number the phone number that needs to be formatted in its original number format * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number * has one * @return the formatted phone number in its original number format */ public String FormatInOriginalFormat(PhoneNumber number, String regionCallingFrom) { if (number.HasRawInput && (HasUnexpectedItalianLeadingZero(number) || !HasFormattingPatternForNumber(number))) { // We check if we have the formatting pattern because without that, we might format the number // as a group without national prefix. return number.RawInput; } if (!number.HasCountryCodeSource) return Format(number, PhoneNumberFormat.NATIONAL); String formattedNumber; switch (number.CountryCodeSource) { case CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN: formattedNumber = Format(number, PhoneNumberFormat.INTERNATIONAL); break; case CountryCodeSource.FROM_NUMBER_WITH_IDD: formattedNumber = FormatOutOfCountryCallingNumber(number, regionCallingFrom); break; case CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN: formattedNumber = Format(number, PhoneNumberFormat.INTERNATIONAL).Substring(1); break; case CountryCodeSource.FROM_DEFAULT_COUNTRY: // Fall-through to default case. default: String regionCode = GetRegionCodeForCountryCode(number.CountryCode); // We strip non-digits from the NDD here, and from the raw input later, so that we can // compare them easily. String nationalPrefix = GetNddPrefixForRegion(regionCode, true /* strip non-digits */); String nationalFormat = Format(number, PhoneNumberFormat.NATIONAL); if (nationalPrefix == null || nationalPrefix.Length == 0) { // If the region doesn't have a national prefix at all, we can safely return the national // format without worrying about a national prefix being added. formattedNumber = nationalFormat; break; } // Otherwise, we check if the original number was entered with a national prefix. if (RawInputContainsNationalPrefix( number.RawInput, nationalPrefix, regionCode)) { // If so, we can safely return the national format. formattedNumber = nationalFormat; break; } PhoneMetadata metadata = GetMetadataForRegion(regionCode); String nationalNumber = GetNationalSignificantNumber(number); NumberFormat formatRule = ChooseFormattingPatternForNumber(metadata.NumberFormatList, nationalNumber); // When the format we apply to this number doesn't contain national prefix, we can just // return the national format. // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired. String candidateNationalPrefixRule = formatRule.NationalPrefixFormattingRule; // We assume that the first-group symbol will never be _before_ the national prefix. int indexOfFirstGroup = candidateNationalPrefixRule.IndexOf("${1}"); if (indexOfFirstGroup <= 0) { formattedNumber = nationalFormat; break; } candidateNationalPrefixRule = candidateNationalPrefixRule.Substring(0, indexOfFirstGroup); candidateNationalPrefixRule = NormalizeDigitsOnly(candidateNationalPrefixRule); if (candidateNationalPrefixRule.Length == 0) { // National prefix not used when formatting this number. formattedNumber = nationalFormat; break; } // Otherwise, we need to remove the national prefix from our output. var numFormatCopy = new NumberFormat.Builder() .MergeFrom(formatRule) .ClearNationalPrefixFormattingRule() .Build(); List<NumberFormat> numberFormats = new List<NumberFormat>(1); numberFormats.Add(numFormatCopy); formattedNumber = FormatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats); break; } String rawInput = number.RawInput; // If no digit is inserted/removed/modified as a result of our formatting, we return the // formatted phone number; otherwise we return the raw input the user entered. return (formattedNumber != null && NormalizeHelper(formattedNumber, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */) .Equals(NormalizeHelper( rawInput, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */))) ? formattedNumber : rawInput; }
/** * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as * a parameter to decrease object creation when invoked many times. */ public void Format(PhoneNumber number, PhoneNumberFormat numberFormat, StringBuilder formattedNumber) { // Clear the StringBuilder first. formattedNumber.Length = 0; var countryCallingCode = number.CountryCode; var nationalSignificantNumber = GetNationalSignificantNumber(number); if (numberFormat == PhoneNumberFormat.E164) { // Early exit for E164 case since no formatting of the national number needs to be applied. // Extensions are not formatted. formattedNumber.Append(nationalSignificantNumber); PrefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164, formattedNumber); return; } // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. var regionCode = GetRegionCodeForCountryCode(countryCallingCode); if (!HasValidCountryCallingCode(countryCallingCode)) { formattedNumber.Append(nationalSignificantNumber); return; } PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCallingCode, regionCode); formattedNumber.Append(FormatNsn(nationalSignificantNumber, metadata, numberFormat)); MaybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber); PrefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber); }
/** * Returns true if the number can be dialled from outside the region, or unknown. If the number * can only be dialled from within the region, returns false. Does not check the number is a valid * number. * TODO: Make this method public when we have enough metadata to make it worthwhile. * * @param number the phone-number for which we want to know whether it is only diallable from * outside the region */ public bool CanBeInternationallyDialled(PhoneNumber number) { String regionCode = GetRegionCodeForNumber(number); if (!IsValidRegionCode(regionCode)) // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always // internationally diallable, and will be caught here. return true; PhoneMetadata metadata = GetMetadataForRegion(regionCode); String nationalSignificantNumber = GetNationalSignificantNumber(number); return !IsNumberMatchingDesc(nationalSignificantNumber, metadata.NoInternationalDialling); }
/** * Appends the formatted extension of a phone number to formattedNumber, if the phone number had * an extension specified. */ private void MaybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata, PhoneNumberFormat numberFormat, StringBuilder formattedNumber) { if (number.HasExtension && number.Extension.Length > 0) { if (numberFormat == PhoneNumberFormat.RFC3966) { formattedNumber.Append(RFC3966_EXTN_PREFIX).Append(number.Extension); } else { if (metadata.HasPreferredExtnPrefix) formattedNumber.Append(metadata.PreferredExtnPrefix).Append(number.Extension); else formattedNumber.Append(DEFAULT_EXTN_PREFIX).Append(number.Extension); } } }
/** * Returns true if a number is from a region whose national significant number couldn't contain a * leading zero, but has the italian_leading_zero field set to true. */ private bool HasUnexpectedItalianLeadingZero(PhoneNumber number) { return number.ItalianLeadingZero && !IsLeadingZeroPossible(number.CountryCode); }
private String GetRegionCodeForNumberFromRegionList(PhoneNumber number, List<String> regionCodes) { String nationalNumber = GetNationalSignificantNumber(number); foreach (var regionCode in regionCodes) { // If leadingDigits is present, use this. Otherwise, do full validation. PhoneMetadata metadata = GetMetadataForRegion(regionCode); if (metadata.HasLeadingDigits) { if (regexCache.GetPatternForRegex(metadata.LeadingDigits) .MatchBeginning(nationalNumber).Success) return regionCode; } else if (GetNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) return regionCode; } return null; }
public bool Verify(Leniency leniency, PhoneNumber number, String candidate, PhoneNumberUtil util) { switch (leniency) { case Leniency.POSSIBLE: return IsPossibleNumber(number); case Leniency.VALID: { if (!util.IsValidNumber(number) || !PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util)) return false; return PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util); } case Leniency.STRICT_GROUPING: { if (!util.IsValidNumber(number) || !PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util) || PhoneNumberMatcher.ContainsMoreThanOneSlash(candidate) || !PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util)) { return false; } return PhoneNumberMatcher.CheckNumberGroupingIsValid( number, candidate, util, (PhoneNumberUtil u, PhoneNumber n, StringBuilder nc, String[] eg) => { return PhoneNumberMatcher.AllNumberGroupsRemainGrouped(u, n, nc, eg); } ); } case Leniency.EXACT_GROUPING: default: { if (!util.IsValidNumber(number) || !PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util) || PhoneNumberMatcher.ContainsMoreThanOneSlash(candidate) || !PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util)) { return false; } return PhoneNumberMatcher.CheckNumberGroupingIsValid( number, candidate, util, (PhoneNumberUtil u, PhoneNumber n, StringBuilder normalizedCandidate, String[] expectedNumberGroups) => { return PhoneNumberMatcher.AllNumberGroupsAreExactlyPresent( u, n, normalizedCandidate, expectedNumberGroups); } ); } } }
/** * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as * a parameter to decrease object creation when invoked many times. */ public void ParseAndKeepRawInput(String numberToParse, String defaultRegion, PhoneNumber.Builder phoneNumber) { ParseHelper(numberToParse, defaultRegion, true, true, phoneNumber); }
/// <summary> /// Gets the PhoneNumberType of the PhoneNumber passed in /// </summary> /// <param name="phoneNumber">PhoneNumber</param> /// <returns>The phone number type</returns> public static PhoneNumberType GetNumberType(this PhoneNumbers.PhoneNumber phoneNumber) { return(PhoneNumbers.PhoneNumberUtil.GetInstance().GetNumberType(phoneNumber)); }
/** * Formats a phone number in national format for dialing using the carrier as specified in the * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing, * use the {@code fallbackCarrierCode} passed in instead. If there is no * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty * string, return the number in national format without any carrier code. * * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting. * * @param number the phone number to be formatted * @param fallbackCarrierCode the carrier selection code to be used, if none is found in the * phone number itself * @return the formatted phone number in national format for dialing using the number's * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if * none is found */ public String FormatNationalNumberWithPreferredCarrierCode(PhoneNumber number, String fallbackCarrierCode) { return FormatNationalNumberWithCarrierCode(number, number.HasPreferredDomesticCarrierCode ? number.PreferredDomesticCarrierCode : fallbackCarrierCode); }
/// <summary> /// Checks if the phonenumber object is mobile number /// </summary> /// <param name="phoneNumber">Phonenumber</param> /// <returns>True if phonenumber is a mobile number</returns> public static bool IsMobileNumber(this PhoneNumbers.PhoneNumber phoneNumber) { return(phoneNumber.GetNumberType() == PhoneNumberType.MOBILE); }
public GenericResponse <ValidatePhoneNumberModel> ValidatePhoneNumber(string telephoneNumber, string countryCode) { //validate-phone-number? number = 00447825152591 & countryCode = GB GenericResponse <ValidatePhoneNumberModel> returnResult; if (string.IsNullOrEmpty(telephoneNumber)) { string errorMessage = "Error : The string supplied did not seem to be a phone number"; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; // throw new ArgumentException(); return(returnResult); } else if ((string.IsNullOrEmpty(countryCode)) || ((countryCode.Length != 2) && (countryCode.Length != 3))) { string errorMessage = "Error : Invalid country calling code"; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; return(returnResult); } else { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse(telephoneNumber, countryCode); bool isMobile = false; bool isValidNumber = phoneUtil.IsValidNumber(phoneNumber); // returns true for valid number bool isValidRegion = phoneUtil.IsValidNumberForRegion(phoneNumber, countryCode); // returns w.r.t phone number region string region = phoneUtil.GetRegionCodeForNumber(phoneNumber); // GB, US , PK var numberType = phoneUtil.GetNumberType(phoneNumber); // Produces Mobile , FIXED_LINE string phoneNumberType = numberType.ToString(); if (!string.IsNullOrEmpty(phoneNumberType) && phoneNumberType == "MOBILE") { isMobile = true; } var originalNumber = phoneUtil.Format(phoneNumber, PhoneNumberFormat.E164); // Produces "+447825152591" var data = new ValidatePhoneNumberModel { FormattedNumber = originalNumber, IsMobile = isMobile, IsValidNumber = isValidNumber, IsValidNumberForRegion = isValidRegion, Region = region }; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Data = data, StatusCode = HttpStatusCode.OK, StatusMessage = "Success" }; } catch (NumberParseException ex) { String errorMessage = "NumberParseException was thrown: " + ex.Message.ToString(); returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; } return(returnResult); } }
public GenericResponse <ValidatePhoneNumberModel> FormatePhoneNumberForDisplay(string telephoneNumber, string dialFrom) { ///format-number-for-display?number=075450175&countryCode=GB&dialFrom=US GenericResponse <ValidatePhoneNumberModel> returnResult; if (string.IsNullOrEmpty(telephoneNumber)) { string errorMessage = "Error : The string supplied did not seem to be a phone number"; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; // throw new ArgumentException(); return(returnResult); } else if ((string.IsNullOrEmpty(dialFrom)) || ((dialFrom.Length != 2) && (dialFrom.Length != 3))) { string errorMessage = "Error : Invalid country calling code"; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; return(returnResult); } else { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse(telephoneNumber, dialFrom); bool isMobile = false; string displayNumber = string.Empty; bool isValidNumber = phoneUtil.IsValidNumber(phoneNumber); // returns true for valid number bool isValidRegion = phoneUtil.IsValidNumberForRegion(phoneNumber, dialFrom); // returns true w.r.t phone number region string region = phoneUtil.GetRegionCodeForNumber(phoneNumber); // GB, US , PK var numberType = phoneUtil.GetNumberType(phoneNumber); // Produces Mobile , FIXED_LINE string phoneNumberType = numberType.ToString(); if (!string.IsNullOrEmpty(phoneNumberType) && phoneNumberType == "MOBILE") { isMobile = true; } if (isValidRegion) { displayNumber = phoneUtil.Format(phoneNumber, PhoneNumberFormat.NATIONAL); // Produces 07825 152591 } else { // Produces International format: +44 7825 152591 //Out - of - country format from US: 011 44 7825 152591 //Out - of - country format from Switzerland: 00 44 7825 152591 displayNumber = phoneUtil.FormatOutOfCountryCallingNumber(phoneNumber, dialFrom); } var data = new ValidatePhoneNumberModel { FormattedNumber = displayNumber, IsMobile = isMobile, IsValidNumber = isValidNumber, IsValidNumberForRegion = isValidRegion, Region = region }; returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Data = data, StatusCode = HttpStatusCode.OK, StatusMessage = "Success" }; } catch (NumberParseException ex) { var errorMessage = "FormatePhoneNumberForDisplay was thrown: " + ex.Message.ToString(); Console.WriteLine(errorMessage); returnResult = new GenericResponse <ValidatePhoneNumberModel>() { Message = errorMessage, StatusCode = HttpStatusCode.BadRequest, StatusMessage = "Failed" }; } return(returnResult); } }
public static Builder CreateBuilder(PhoneNumber prototype) { return(new Builder().MergeFrom(prototype)); }
public async Task <IActionResult> DirectSignUpWithMobile([FromBody] SignUpWithMobileViewModel model) { SignUpMobileWithOTPResponse response = new SignUpMobileWithOTPResponse(); PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); string countryCode = "IN"; PhoneNumbers.PhoneNumber phoneNumber = phoneUtil.Parse(model.Mobile, countryCode); bool isValidNumber = phoneUtil.IsValidNumber(phoneNumber); // returns true for valid number if (!isValidNumber) { response.ReturnCode = 200; response.ReturnMsg = "This mobile number is not Valid"; response.ErrorCode = 401; response.StatusCode = 200; response.StatusMessage = "error"; return(Ok(response)); // return Ok("This mobile number is Valid"); } bool IsSignMobile = _userdata.GetMobileNumber(model.Mobile); if (IsSignMobile) { /* * var currentUser = new ApplicationUser * { * Mobile = model.Mobile, * UserName = model.Mobile, * OTP = _userdata.GenerateRandomOTP() * }; * * var result = await _userManager.CreateAsync(currentUser); * if (result.Succeeded) * { * var officeClaim = new Claim(OpenIdConnectConstants.Claims.PhoneNumber, currentUser.Mobile, ClaimValueTypes.Integer); * await _userManager.AddClaimAsync(currentUser, officeClaim); * // Add to roles * var roleAddResult = await _userManager.AddToRoleAsync(currentUser, "User"); * * if (roleAddResult.Succeeded) * { * //await _messageSender.SendSMSAsync(model.Mobile, ""); * SignUpMobileWithOTPResponse response = new SignUpMobileWithOTPResponse(); * response.ReturnCode = 200; * response.ReturnMsg = "Success"; * response.StatusCode = 200; * response.StatusMessage = "Done"; * return Ok(response); * } * } * AddErrors(result); */ response.ReturnCode = 200; response.ReturnMsg = "Success"; response.StatusCode = 200; response.StatusMessage = "Done"; return(Ok(response)); } else { ModelState.AddModelError(string.Empty, "This mobile number is already registered."); return(BadRequest(new ApiError(ModelState))); } // If we got this far, something failed, redisplay form return(BadRequest(new ApiError(ModelState))); }
/// <summary> /// Tries get the PhoneNumber object if the phonenumber is a valid phoneNumber for the regions specified /// </summary> /// <param name="phoneUtil"></param> /// <param name="numberString"></param> /// <param name="regionCodes">The region code for global networks</param> /// <param name="phoneNumber">PhoneNumber object</param> /// <returns>True if successful; else false</returns> public static bool TryGetValidMobileNumber(this PhoneNumbers.PhoneNumberUtil phoneUtil, string numberString, string[] regionCodes, out PhoneNumbers.PhoneNumber phoneNumber) { phoneNumber = null; var number = phoneUtil.GetValidNumber(numberString, regionCodes); if (number == null) { return(false); } return(phoneUtil.GetNumberType(number) == PhoneNumberType.MOBILE); }
/** * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to * decrease object creation when invoked many times. */ public void Parse(String numberToParse, String defaultRegion, PhoneNumber.Builder phoneNumber) { ParseHelper(numberToParse, defaultRegion, false, true, phoneNumber); }
/// <summary> /// Tries get a valid number for the regions passed in /// </summary> /// <param name="phoneUtil">PhoneUtil instance</param> /// <param name="numberString">Phonenumber</param> /// <param name="regionCodes">The region code for global networks</param> /// <param name="phoneNumber">PhoneNumbers.PhoneNumber object of the number passed in</param> /// <returns>True if successful; else false</returns> public static bool TryGetValidNumber(this PhoneNumbers.PhoneNumberUtil phoneUtil, string numberString, string[] regionCodes, out PhoneNumbers.PhoneNumber phoneNumber) { phoneNumber = null; foreach (var regionCode in regionCodes) { phoneNumber = ParseFromString(phoneUtil, numberString, regionCode); if (phoneNumber == null) { continue; } if (phoneUtil.IsValidNumberForRegion(phoneNumber, regionCode)) { return(true); } } return(false); }
/** * Attempts to extract a valid number from a phone number that is too long to be valid, and resets * the PhoneNumber object passed in to that valid version. If no valid number could be extracted, * the PhoneNumber object passed in will not be modified. * @param number a PhoneNumber object which contains a number that is too long to be valid. * @return true if a valid phone number can be successfully extracted. */ public bool TruncateTooLongNumber(PhoneNumber.Builder number) { if (IsValidNumber(number.Clone().Build())) return true; PhoneNumber copy = null; ulong nationalNumber = number.NationalNumber; do { nationalNumber /= 10; PhoneNumber.Builder numberCopy = number.Clone(); numberCopy.SetNationalNumber(nationalNumber); copy = numberCopy.Build(); if (IsPossibleNumberWithReason(copy) == ValidationResult.TOO_SHORT || nationalNumber == 0) return false; } while (!IsValidNumber(copy)); number.SetNationalNumber(nationalNumber); return true; }
/** * Gets the national significant number of the a phone number. Note a national significant number * doesn't contain a national prefix or any formatting. * * @param number the PhoneNumber object for which the national significant number is needed * @return the national significant number of the PhoneNumber object passed in */ public String GetNationalSignificantNumber(PhoneNumber number) { // If a leading zero has been set, we prefix this now. Note this is not a national prefix. StringBuilder nationalNumber = new StringBuilder(number.ItalianLeadingZero ? "0" : ""); nationalNumber.Append(number.NationalNumber); return nationalNumber.ToString(); }
private static bool AreEqual(PhoneNumber.Builder p1, PhoneNumber.Builder p2) { return p1.Clone().Build().Equals(p2.Clone().Build()); }
/** * Gets the type of a phone number. * * @param number the phone number that we want to know the type * @return the type of the phone number */ public PhoneNumberType GetNumberType(PhoneNumber number) { var regionCode = GetRegionCodeForNumber(number); if (!IsValidRegionCode(regionCode) && !REGION_CODE_FOR_NON_GEO_ENTITY.Equals(regionCode)) return PhoneNumberType.UNKNOWN; var nationalSignificantNumber = GetNationalSignificantNumber(number); PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(number.CountryCode, regionCode); return GetNumberTypeHelper(nationalSignificantNumber, metadata); }
private bool HasFormattingPatternForNumber(PhoneNumber number) { int countryCallingCode = number.CountryCode; String phoneNumberRegion = GetRegionCodeForCountryCode(countryCallingCode); PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion); if (metadata == null) { return false; } String nationalNumber = GetNationalSignificantNumber(number); NumberFormat formatRule = ChooseFormattingPatternForNumber(metadata.NumberFormatList, nationalNumber); return formatRule != null; }
/** * Returns the region where a phone number is from. This could be used for geocoding at the region * level. * * @param number the phone number whose origin we want to know * @return the region where the phone number is from, or null if no region matches this calling * code */ public String GetRegionCodeForNumber(PhoneNumber number) { List<String> regions = null; countryCallingCodeToRegionCodeMap_.TryGetValue(number.CountryCode, out regions); if (regions == null) { // String numberString = getNationalSignificantNumber(number); // LOGGER.log(Level.WARNING, // "Missing/invalid country_code (" + countryCode + ") for number " + numberString); return null; } if (regions.Count == 1) return regions[0]; return GetRegionCodeForNumberFromRegionList(number, regions); }
// Returns true when one national number is the suffix of the other or both are the same. private bool IsNationalNumberSuffixOfTheOther(PhoneNumber.Builder firstNumber, PhoneNumber.Builder secondNumber) { String firstNumberNationalNumber = firstNumber.NationalNumber.ToString(); String secondNumberNationalNumber = secondNumber.NationalNumber.ToString(); // Note that endsWith returns true if the numbers are equal. return firstNumberNationalNumber.EndsWith(secondNumberNationalNumber) || secondNumberNationalNumber.EndsWith(firstNumberNationalNumber); }
/** * Takes two phone numbers and compares them for equality. * * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers * and any extension present are the same. * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are * the same. * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is * the same, and one NSN could be a shorter version of the other number. This includes the case * where one has an extension specified, and the other does not. * Returns NO_MATCH otherwise. * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. * * @param firstNumberIn first number to compare * @param secondNumberIn second number to compare * * @return NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality * of the two numbers, described in the method definition. */ public MatchType IsNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) { // Make copies of the phone number so that the numbers passed in are not edited. var firstNumber = new PhoneNumber.Builder(); firstNumber.MergeFrom(firstNumberIn); var secondNumber = new PhoneNumber.Builder(); secondNumber.MergeFrom(secondNumberIn); // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any // empty-string extensions so that we can use the proto-buffer equality method. firstNumber.ClearRawInput(); firstNumber.ClearCountryCodeSource(); firstNumber.ClearPreferredDomesticCarrierCode(); secondNumber.ClearRawInput(); secondNumber.ClearCountryCodeSource(); secondNumber.ClearPreferredDomesticCarrierCode(); if (firstNumber.HasExtension && firstNumber.Extension.Length == 0) firstNumber.ClearExtension(); if (secondNumber.HasExtension && secondNumber.Extension.Length == 0) secondNumber.ClearExtension(); // Early exit if both had extensions and these are different. if (firstNumber.HasExtension && secondNumber.HasExtension && !firstNumber.Extension.Equals(secondNumber.Extension)) return MatchType.NO_MATCH; int firstNumberCountryCode = firstNumber.CountryCode; int secondNumberCountryCode = secondNumber.CountryCode; // Both had country_code specified. if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) { if (AreEqual(firstNumber, secondNumber)) return MatchType.EXACT_MATCH; else if (firstNumberCountryCode == secondNumberCountryCode && IsNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) { // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a // shorter variant of the other. return MatchType.SHORT_NSN_MATCH; } // This is not a match. return MatchType.NO_MATCH; } // Checks cases where one or both country_code fields were not specified. To make equality // checks easier, we first set the country_code fields to be equal. firstNumber.SetCountryCode(secondNumberCountryCode); // If all else was the same, then this is an NSN_MATCH. if (AreEqual(firstNumber, secondNumber)) return MatchType.NSN_MATCH; if (IsNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) return MatchType.SHORT_NSN_MATCH; return MatchType.NO_MATCH; }
/** * Parses a string and fills up the phoneNumber. This method is the same as the public * parse() method, with the exception that it allows the default region to be null, for use by * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region * to be null or unknown ("ZZ"). */ private void ParseHelper(String numberToParse, String defaultRegion, bool keepRawInput, bool checkRegion, PhoneNumber.Builder phoneNumber) { if (numberToParse == null) throw new NumberParseException(ErrorType.NOT_A_NUMBER, "The phone number supplied was null."); else if (numberToParse.Length > MAX_INPUT_STRING_LENGTH) throw new NumberParseException(ErrorType.TOO_LONG, "The string supplied was too long to parse."); StringBuilder nationalNumber = new StringBuilder(); BuildNationalNumberForParsing(numberToParse, nationalNumber); if (!IsViablePhoneNumber(nationalNumber.ToString())) throw new NumberParseException(ErrorType.NOT_A_NUMBER, "The string supplied did not seem to be a phone number."); // Check the region supplied is valid, or that the extracted number starts with some sort of + // sign so the number's region can be determined. if (checkRegion && !CheckRegionForParsing(nationalNumber.ToString(), defaultRegion)) throw new NumberParseException(ErrorType.INVALID_COUNTRY_CODE, "Missing or invalid default region."); if (keepRawInput) phoneNumber.SetRawInput(numberToParse); // Attempt to parse extension first, since it doesn't require region-specific data and we want // to have the non-normalised number here. String extension = MaybeStripExtension(nationalNumber); if (extension.Length > 0) phoneNumber.SetExtension(extension); PhoneMetadata regionMetadata = GetMetadataForRegion(defaultRegion); // Check to see if the number is given in international format so we know whether this number is // from the default region or not. StringBuilder normalizedNationalNumber = new StringBuilder(); int countryCode = 0; try { // TODO: This method should really just take in the string buffer that has already // been created, and just remove the prefix, rather than taking in a string and then // outputting a string buffer. countryCode = MaybeExtractCountryCode(nationalNumber.ToString(), regionMetadata, normalizedNationalNumber, keepRawInput, phoneNumber); } catch (NumberParseException e) { var m = PLUS_CHARS_PATTERN.MatchBeginning(nationalNumber.ToString()); if (e.ErrorType == ErrorType.INVALID_COUNTRY_CODE && m.Success) { // Strip the plus-char, and try again. countryCode = MaybeExtractCountryCode( nationalNumber.ToString().Substring(m.Index + m.Length), regionMetadata, normalizedNationalNumber, keepRawInput, phoneNumber); if (countryCode == 0) { throw new NumberParseException(ErrorType.INVALID_COUNTRY_CODE, "Could not interpret numbers after plus-sign."); } } else { throw new NumberParseException(e.ErrorType, e.Message); } } if (countryCode != 0) { String phoneNumberRegion = GetRegionCodeForCountryCode(countryCode); if (phoneNumberRegion != defaultRegion) regionMetadata = GetMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion); } else { // If no extracted country calling code, use the region supplied instead. The national number // is just the normalized version of the number we were given to parse. Normalize(nationalNumber); normalizedNationalNumber.Append(nationalNumber); if (defaultRegion != null) { countryCode = regionMetadata.CountryCode; phoneNumber.SetCountryCode(countryCode); } else if (keepRawInput) { phoneNumber.ClearCountryCode(); } } if (normalizedNationalNumber.Length < MIN_LENGTH_FOR_NSN) throw new NumberParseException(ErrorType.TOO_SHORT_NSN, "The string supplied is too short to be a phone number."); if (regionMetadata != null) { StringBuilder carrierCode = new StringBuilder(); MaybeStripNationalPrefixAndCarrierCode(normalizedNationalNumber, regionMetadata, carrierCode); if (keepRawInput) phoneNumber.SetPreferredDomesticCarrierCode(carrierCode.ToString()); } int lengthOfNationalNumber = normalizedNationalNumber.Length; if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) throw new NumberParseException(ErrorType.TOO_SHORT_NSN, "The string supplied is too short to be a phone number."); if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) throw new NumberParseException(ErrorType.TOO_LONG, "The string supplied is too long to be a phone number."); if (normalizedNationalNumber[0] == '0') phoneNumber.SetItalianLeadingZero(true); phoneNumber.SetNationalNumber(ulong.Parse(normalizedNationalNumber.ToString())); }
/** * Takes two phone numbers and compares them for equality. This is a convenience wrapper for * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known. * * @param firstNumber first number to compare in proto buffer format. * @param secondNumber second number to compare. Can contain formatting, and can have country * calling code specified with + at the start. * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details. */ public MatchType IsNumberMatch(PhoneNumber firstNumber, String secondNumber) { // First see if the second number has an implicit country calling code, by attempting to parse // it. try { PhoneNumber secondNumberAsProto = Parse(secondNumber, UNKNOWN_REGION); return IsNumberMatch(firstNumber, secondNumberAsProto); } catch (NumberParseException e) { if (e.ErrorType == ErrorType.INVALID_COUNTRY_CODE) { // The second number has no country calling code. EXACT_MATCH is no longer possible. // We parse it as if the region was the same as that for the first number, and if // EXACT_MATCH is returned, we replace this with NSN_MATCH. String firstNumberRegion = GetRegionCodeForCountryCode(firstNumber.CountryCode); try { if (!firstNumberRegion.Equals(UNKNOWN_REGION)) { PhoneNumber secondNumberWithFirstNumberRegion = Parse(secondNumber, firstNumberRegion); MatchType match = IsNumberMatch(firstNumber, secondNumberWithFirstNumberRegion); if (match == MatchType.EXACT_MATCH) return MatchType.NSN_MATCH; return match; } else { // If the first number didn't have a valid country calling code, then we parse the // second number without one as well. var secondNumberProto = new PhoneNumber.Builder(); ParseHelper(secondNumber, null, false, false, secondNumberProto); return IsNumberMatch(firstNumber, secondNumberProto.Build()); } } catch (NumberParseException) { // Fall-through to return NOT_A_NUMBER. } } } // One or more of the phone numbers we are trying to match is not a viable phone number. return MatchType.NOT_A_NUMBER; }
/** * Formats a phone number in the specified format using default rules. Note that this does not * promise to produce a phone number that the user can dial from where they are - although we do * format in either 'national' or 'international' format depending on what the client asks for, we * do not currently support a more abbreviated format, such as for users in the same "area" who * could potentially dial the number without area code. Note that if the phone number has a * country calling code of 0 or an otherwise invalid country calling code, we cannot work out * which formatting rules to apply so we return the national significant number with no formatting * applied. * * @param number the phone number to be formatted * @param numberFormat the format the phone number should be formatted into * @return the formatted phone number */ public String Format(PhoneNumber number, PhoneNumberFormat numberFormat) { if (number.NationalNumber == 0 && number.HasRawInput) { String rawInput = number.RawInput; if (rawInput.Length > 0) { return rawInput; } } var formattedNumber = new StringBuilder(20); Format(number, numberFormat, formattedNumber); return formattedNumber.ToString(); }
/** * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason * for failure, this method returns a boolean value. * @param number the number that needs to be checked * @return true if the number is possible */ public bool IsPossibleNumber(PhoneNumber number) { return IsPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE; }
/** * Formats a phone number in the specified format using client-defined formatting rules. Note that * if the phone number has a country calling code of zero or an otherwise invalid country calling * code, we cannot work out things like whether there should be a national prefix applied, or how * to format extensions, so we return the national significant number with no formatting applied. * * @param number the phone number to be formatted * @param numberFormat the format the phone number should be formatted into * @param userDefinedFormats formatting rules specified by clients * @return the formatted phone number */ public String FormatByPattern(PhoneNumber number, PhoneNumberFormat numberFormat, List<NumberFormat> userDefinedFormats) { int countryCallingCode = number.CountryCode; var nationalSignificantNumber = GetNationalSignificantNumber(number); // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. var regionCode = GetRegionCodeForCountryCode(countryCallingCode); if (!HasValidCountryCallingCode(countryCallingCode)) return nationalSignificantNumber; PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCallingCode, regionCode); StringBuilder formattedNumber = new StringBuilder(20); NumberFormat formattingPattern = ChooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber); if (formattingPattern == null) { // If no pattern above is matched, we format the number as a whole. formattedNumber.Append(nationalSignificantNumber); } else { var numFormatCopy = new NumberFormat.Builder(); // Before we do a replacement of the national prefix pattern $NP with the national prefix, we // need to copy the rule so that subsequent replacements for different numbers have the // appropriate national prefix. numFormatCopy.MergeFrom(formattingPattern); String nationalPrefixFormattingRule = formattingPattern.NationalPrefixFormattingRule; if (nationalPrefixFormattingRule.Length > 0) { String nationalPrefix = metadata.NationalPrefix; if (nationalPrefix.Length > 0) { // Replace $NP with national prefix and $FG with the first group ($1). nationalPrefixFormattingRule = NP_PATTERN.Replace(nationalPrefixFormattingRule, nationalPrefix, 1); nationalPrefixFormattingRule = FG_PATTERN.Replace(nationalPrefixFormattingRule, "$$1", 1); numFormatCopy.SetNationalPrefixFormattingRule(nationalPrefixFormattingRule); } else { // We don't want to have a rule for how to format the national prefix if there isn't one. numFormatCopy.ClearNationalPrefixFormattingRule(); } } formattedNumber.Append( FormatNsnUsingPattern(nationalSignificantNumber, numFormatCopy.Build(), numberFormat)); } MaybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber); PrefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber); return formattedNumber.ToString(); }
/** * Check whether a phone number is a possible number. It provides a more lenient check than * {@link #isValidNumber} in the following sense: *<ol> * <li> It only checks the length of phone numbers. In particular, it doesn't check starting * digits of the number. * <li> It doesn't attempt to figure out the type of the number, but uses general rules which * applies to all types of phone numbers in a region. Therefore, it is much faster than * isValidNumber. * <li> For fixed line numbers, many regions have the concept of area code, which together with * subscriber number constitute the national significant number. It is sometimes okay to dial * the subscriber number only when dialing in the same area. This function will return * true if the subscriber-number-only version is passed in. On the other hand, because * isValidNumber validates using information on both starting digits (for fixed line * numbers, that would most likely be area codes) and length (obviously includes the * length of area codes for fixed line numbers), it will return false for the * subscriber-number-only version. * </ol * @param number the number that needs to be checked * @return a ValidationResult object which indicates whether the number is possible */ public ValidationResult IsPossibleNumberWithReason(PhoneNumber number) { var nationalNumber = GetNationalSignificantNumber(number); int countryCode = number.CountryCode; // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or // Russia) since the getRegionCodeForNumber will not work if the number is possible but not // valid. This would need to be revisited if the possible number pattern ever differed between // various regions within those plans. if (!HasValidCountryCallingCode(countryCode)) return ValidationResult.INVALID_COUNTRY_CODE; String regionCode = GetRegionCodeForCountryCode(countryCode); PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCode, regionCode); PhoneNumberDesc generalNumDesc = metadata.GeneralDesc; // Handling case of numbers with no metadata. if (!generalNumDesc.HasNationalNumberPattern) { int numberLength = nationalNumber.Length; if (numberLength < MIN_LENGTH_FOR_NSN) return ValidationResult.TOO_SHORT; if (numberLength > MAX_LENGTH_FOR_NSN) return ValidationResult.TOO_LONG; return ValidationResult.IS_POSSIBLE; } var possibleNumberPattern = regexCache.GetPatternForRegex(generalNumDesc.PossibleNumberPattern); return TestNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber); }
/** * Formats a phone number in national format for dialing using the carrier as specified in the * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the * phone number already has a preferred domestic carrier code stored. If {@code carrierCode} * contains an empty string, returns the number in national format without any carrier code. * * @param number the phone number to be formatted * @param carrierCode the carrier selection code to be used * @return the formatted phone number in national format for dialing using the carrier as * specified in the {@code carrierCode} */ public String FormatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) { var countryCallingCode = number.CountryCode; var nationalSignificantNumber = GetNationalSignificantNumber(number); // Note getRegionCodeForCountryCode() is used because formatting information for regions which // share a country calling code is contained by only one region for performance reasons. For // example, for NANPA regions it will be contained in the metadata for US. var regionCode = GetRegionCodeForCountryCode(countryCallingCode); if (!HasValidCountryCallingCode(countryCallingCode)) return nationalSignificantNumber; var formattedNumber = new StringBuilder(20); PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCallingCode, regionCode); formattedNumber.Append(FormatNsn(nationalSignificantNumber, metadata, PhoneNumberFormat.NATIONAL, carrierCode)); MaybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber); PrefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL, formattedNumber); return formattedNumber.ToString(); }
/** * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number * is actually in use, which is impossible to tell by just looking at a number itself. * * @param number the phone number that we want to validate * @return a boolean that indicates whether the number is of a valid pattern */ public bool IsValidNumber(PhoneNumber number) { var regionCode = GetRegionCodeForNumber(number); return IsValidNumberForRegion(number, regionCode); }
/** * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number * is actually in use, which is impossible to tell by just looking at a number itself. If the * country calling code is not the same as the country calling code for the region, this * immediately exits with false. After this, the specific number pattern rules for the region are * examined. This is useful for determining for example whether a particular number is valid for * Canada, rather than just a valid NANPA number. * * @param number the phone number that we want to validate * @param regionCode the region that we want to validate the phone number for * @return a boolean that indicates whether the number is of a valid pattern */ public bool IsValidNumberForRegion(PhoneNumber number, String regionCode) { int countryCode = number.CountryCode; PhoneMetadata metadata = GetMetadataForRegionOrCallingCode(countryCode, regionCode); if ((metadata == null) || (!REGION_CODE_FOR_NON_GEO_ENTITY.Equals(regionCode) && countryCode != GetCountryCodeForValidRegion(regionCode))) { // Either the region code was invalid, or the country calling code for this number does not // match that of the region code. return false; } var generalNumDesc = metadata.GeneralDesc; var nationalSignificantNumber = GetNationalSignificantNumber(number); // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in // as a valid number if its national significant number is between the minimum and maximum // lengths defined by ITU for a national significant number. if (!generalNumDesc.HasNationalNumberPattern) { int numberLength = nationalSignificantNumber.Length; return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN; } return GetNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN; }
/** * Tries to extract a country calling code from a number. This method will return zero if no * country calling code is considered to be present. Country calling codes are extracted in the * following ways: * <ul> * <li> by stripping the international dialing prefix of the region the person is dialing from, * if this is present in the number, and looking at the next digits * <li> by stripping the '+' sign if present and then looking at the next digits * <li> by comparing the start of the number and the country calling code of the default region. * If the number is not considered possible for the numbering plan of the default region * initially, but starts with the country calling code of this region, validation will be * reattempted after stripping this country calling code. If this number is considered a * possible number, then the first digits will be considered the country calling code and * removed as such. * </ul> * It will throw a NumberParseException if the number starts with a '+' but the country calling * code supplied after this does not match that of any known region. * * @param number non-normalized telephone number that we wish to extract a country calling * code from - may begin with '+' * @param defaultRegionMetadata metadata about the region this number may be from * @param nationalNumber a string buffer to store the national significant number in, in the case * that a country calling code was extracted. The number is appended to any existing contents. * If no country calling code was extracted, this will be left unchanged. * @param keepRawInput true if the country_code_source and preferred_carrier_code fields of * phoneNumber should be populated. * @param phoneNumber the PhoneNumber object where the country_code and country_code_source need * to be populated. Note the country_code is always populated, whereas country_code_source is * only populated when keepCountryCodeSource is true. * @return the country calling code extracted or 0 if none could be extracted */ public int MaybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata, StringBuilder nationalNumber, bool keepRawInput, PhoneNumber.Builder phoneNumber) { if (number.Length == 0) return 0; StringBuilder fullNumber = new StringBuilder(number); // Set the default prefix to be something that will never match. String possibleCountryIddPrefix = "NonMatch"; if (defaultRegionMetadata != null) { possibleCountryIddPrefix = defaultRegionMetadata.InternationalPrefix; } CountryCodeSource countryCodeSource = MaybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix); if (keepRawInput) { phoneNumber.SetCountryCodeSource(countryCodeSource); } if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) { if (fullNumber.Length <= MIN_LENGTH_FOR_NSN) { throw new NumberParseException(ErrorType.TOO_SHORT_AFTER_IDD, "Phone number had an IDD, but after this was not " + "long enough to be a viable phone number."); } int potentialCountryCode = ExtractCountryCode(fullNumber, nationalNumber); if (potentialCountryCode != 0) { phoneNumber.SetCountryCode(potentialCountryCode); return potentialCountryCode; } // If this fails, they must be using a strange country calling code that we don't recognize, // or that doesn't exist. throw new NumberParseException(ErrorType.INVALID_COUNTRY_CODE, "Country calling code supplied was not recognised."); } else if (defaultRegionMetadata != null) { // Check to see if the number starts with the country calling code for the default region. If // so, we remove the country calling code, and do some checks on the validity of the number // before and after. int defaultCountryCode = defaultRegionMetadata.CountryCode; String defaultCountryCodeString = defaultCountryCode.ToString(); String normalizedNumber = fullNumber.ToString(); if (normalizedNumber.StartsWith(defaultCountryCodeString)) { StringBuilder potentialNationalNumber = new StringBuilder(normalizedNumber.Substring(defaultCountryCodeString.Length)); PhoneNumberDesc generalDesc = defaultRegionMetadata.GeneralDesc; var validNumberPattern = regexCache.GetPatternForRegex(generalDesc.NationalNumberPattern); MaybeStripNationalPrefixAndCarrierCode( potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */); var possibleNumberPattern = regexCache.GetPatternForRegex(generalDesc.PossibleNumberPattern); // If the number was not valid before but is valid now, or if it was too long before, we // consider the number with the country calling code stripped to be a better result and // keep that instead. if ((!validNumberPattern.MatchAll(fullNumber.ToString()).Success && //XXX: ToString validNumberPattern.MatchAll(potentialNationalNumber.ToString()).Success) || //XXX: ToString TestNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.ToString()) == ValidationResult.TOO_LONG) { nationalNumber.Append(potentialNationalNumber); if (keepRawInput) phoneNumber.SetCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN); phoneNumber.SetCountryCode(defaultCountryCode); return defaultCountryCode; } } } // No country calling code present. phoneNumber.SetCountryCode(0); return 0; }
/** * Returns the description of the geographical area the {@code number} corresponds to. This method * distinguishes the case of an invalid prefix and a prefix for which the name is not available in * the current language. If the description is not available in the current language an empty * string is returned. If no description was found for the provided number, null is returned. * * @param number the phone number to look up * @return the description of the geographical area */ public String Lookup(PhoneNumber number) { int numOfEntries = areaCodeMapStorage.getNumOfEntries(); if (numOfEntries == 0) { return null; } long phonePrefix = long.Parse(number.CountryCode + phoneUtil.GetNationalSignificantNumber(number)); int currentIndex = numOfEntries - 1; List<int> currentSetOfLengths = areaCodeMapStorage.getPossibleLengths(); var length = currentSetOfLengths.Count; while (length > 0) { int possibleLength = currentSetOfLengths[length - 1]; String phonePrefixStr = phonePrefix.ToString(); if (phonePrefixStr.Length > possibleLength) { phonePrefix = long.Parse(phonePrefixStr.Substring(0, possibleLength)); } currentIndex = binarySearch(0, currentIndex, phonePrefix); if (currentIndex < 0) { return null; } int currentPrefix = areaCodeMapStorage.getPrefix(currentIndex); if (phonePrefix == currentPrefix) { return areaCodeMapStorage.getDescription(currentIndex); } while (length > 0 && currentSetOfLengths[length - 1] >= possibleLength) length--; } return null; }
/** * Returns the customary display name in the given language for the given territory the phone * number is from. */ private String GetCountryNameForNumber(PhoneNumber number, Locale language) { String regionCode = phoneUtil.GetRegionCodeForNumber(number); return(GetRegionDisplayName(regionCode, language)); }