public string Validate(string value) { logger.Debug($"Validate():value={value}"); if (string.IsNullOrEmpty(value)) { if (this.allowNull) { return(value); } throw new Exception($"Field {this.name} cannot be null"); } var phoneNumber = PHONE_NUMBER_UTIL.Parse(value, "US"); if (!PHONE_NUMBER_UTIL.IsValidNumber(phoneNumber)) { throw new Exception($"Invalid {this.name} number"); } var formattedPhoneNumber = PHONE_NUMBER_UTIL.Format(phoneNumber, PhoneNumberFormat.E164); var result = NON_PHONE_CHARS.Replace(formattedPhoneNumber, "").Trim(); logger.Debug($"Validate():result={result}"); return(result); }
public static bool TryParse(string phoneNumberToParse, out CanonicalPhoneNumber phoneNumber, string iso2CountryCode = "US") { phoneNumber = null; if (string.IsNullOrEmpty(phoneNumberToParse)) { return(false); } phoneNumberToParse = phoneNumberToParse.Trim(); if (phoneNumberToParse.StartsWith("00")) { phoneNumberToParse = String.Concat("+", phoneNumberToParse.Remove(0, 2)); } PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumber number = phoneUtil.Parse(phoneNumberToParse, phoneNumberToParse.StartsWith("+") ? null : iso2CountryCode); if (phoneUtil.IsValidNumber(number)) { phoneNumber = new CanonicalPhoneNumber(); if (number.HasCountryCode) { phoneNumber.CountryCode = number.CountryCode; } phoneNumber.E164PhoneNumber = phoneUtil.Format(number, PhoneNumberFormat.E164); phoneNumber.Iso2CountryCode = phoneUtil.GetRegionCodeForNumber(number); phoneNumber.InternationalPhoneNumber = phoneUtil.Format(number, PhoneNumberFormat.INTERNATIONAL); phoneNumber.NationalPhoneNumber = phoneUtil.Format(number, PhoneNumberFormat.NATIONAL); // We probably not needed now, but is here, if you need it at a later date. // string rfc3966Number = phoneUtil.Format(number, PhoneNumberFormat.RFC3966); return(true); } } catch (NumberParseException exception) { // TODO: Log exception if you care about it. Console.WriteLine($"Error parsing phone number: {exception.Message}"); return(false); } return(false); }
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"); } } }
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]", "")); }
string HidePhoneNumber(string phoneNumber, int hideLimit = 5) { PhoneNumberUtil numberUtil = PhoneNumberUtil.GetInstance(); PhoneNumber number = numberUtil.Parse(phoneNumber, "NG"); phoneNumber = numberUtil.Format(number, PhoneNumberFormat.INTERNATIONAL); string resultNumber = ""; int limit = phoneNumber.Length - 1; int hiddenCount = 0; for (int i = limit; i >= 0; i--) { // display the last two characters in the phone number if (i > limit - 2) { resultNumber = phoneNumber[i] + resultNumber; } // hide the next set of numbers till the limit is reached else if (char.IsNumber(phoneNumber[i]) && hiddenCount < hideLimit) { hiddenCount++; resultNumber = "*" + resultNumber; } // Add everything else else { resultNumber = phoneNumber[i] + resultNumber; } } return(resultNumber); }
public async void ValidatePhoneAsync() { 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); PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.GetInstance(); if (phoneUtil.IsValidNumber(phonenumberObject)) { PhoneNumberEnrichInformatica(phoneUtil.Format(phonenumberObject, PhoneNumberFormat.E164)); } }); } catch (Exception ex) { MessageBox.Show("Exception Occured :" + ex.StackTrace); btnValidate.Text = "Validate"; } } }
private long ParseNumberAsLong(string originalNumber) { string countryCode; CTTelephonyNetworkInfo info = new CTTelephonyNetworkInfo(); CTCarrier carrier = info.SubscriberCellularProvider; if (carrier != null) { countryCode = carrier.IsoCountryCode.ToUpper(); } else { countryCode = "US"; } PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); PhoneNumber number = util.Parse(originalNumber, countryCode); string normalizedNumber = util.Format(number, PhoneNumberFormat.E164); StringBuilder builder = new StringBuilder(); foreach (char c in normalizedNumber) { if (char.IsDigit(c)) { builder.Append(c); } } return(long.Parse(builder.ToString())); }
static Boolean parse([MarshalAs(UnmanagedType.BStr)] String number, [MarshalAs(UnmanagedType.BStr)] String country, [MarshalAs(UnmanagedType.BStr)] out String formatetNumber) { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumber phonenumber = phoneUtil.Parse(number, country); formatetNumber = phoneUtil.Format(phonenumber, PhoneNumberFormat.INTERNATIONAL); return(true); } catch (Exception e) { formatetNumber = e.Message; return(false); } // Produces "+41 44 668 18 00" //System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL)); // Produces "044 668 18 00" //System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL)); // Produces "+41446681800" //System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164)); }
/** * Helper method to get the national-number part of a number, formatted without any national * prefix, and return it as a set of digit blocks that would be formatted together. */ private static String[] GetNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number, NumberFormat formattingPattern) { if (formattingPattern == null) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. String rfc3966Format = util.Format(number, PhoneNumberFormat.RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. int endIndex = rfc3966Format.IndexOf(';'); if (endIndex < 0) { endIndex = rfc3966Format.Length; } // The country-code will have a '-' following it. int startIndex = rfc3966Format.IndexOf('-') + 1; return(rfc3966Format.Substring(startIndex, endIndex - startIndex).Split(new [] { '-' })); } else { // We format the NSN only, and split that according to the separator. String nationalSignificantNumber = util.GetNationalSignificantNumber(number); return(util.FormatNsnUsingPattern(nationalSignificantNumber, formattingPattern, PhoneNumberFormat.RFC3966).Split(new [] { '-' })); } }
public static string ConcatonatePhoneWithCc(string phone, string CountryCodeName) { //Change Data Phone PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); PhoneNumber swissNumberProto = phoneUtil.Parse(phone, CountryCodeName); return(phoneUtil.Format(swissNumberProto, PhoneNumberFormat.E164)); }
public static string FormatNumberByCountryCode(string number, string countryCode) { number = number.Replace("+", string.Empty); var protoNumber = PhoneUtil.Parse(number, countryCode); var formattedNumber = PhoneUtil.Format(protoNumber, PhoneNumberFormat.E164); return(formattedNumber); }
private User ParseUser(string content) { var fields = content.Split('\t'); return(new User { Name = fields[0], Birthday = DateTime.ParseExact(fields[1], "dd.MM.yy", CultureInfo.InvariantCulture), Email = fields[2].ToLower(), Phone = _phoneUtil.Format(_phoneUtil.Parse(fields[3], "RU"), PhoneNumberFormat.INTERNATIONAL) }); }
private string FormatNumber(string phone) { var number = _phoneUtil.Parse(phone, "GB"); if (!_phoneUtil.IsValidNumber(number)) { throw new Exception($"Invalid phone number: {phone}"); } _phoneUtil.FormatOutOfCountryCallingNumber(number, "GB"); return(_phoneUtil.Format(number, PhoneNumberFormat.E164).Replace("+", "")); }
public static string formatNumberInternational(string number) { try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); PhoneNumber parsedNumber = util.Parse(number, null); return(util.Format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)); } catch (NumberParseException e) { //Log.w(TAG, e); return(number); } }
/// <summary> /// Returns a formatted user-displayable phone number (including spaces, parentheses, etc.) /// </summary> /// <param name="phoneNumber">The phone number to format.</param> /// <returns>Returns a formatted user-displayable phone number.</returns> /// <remarks>National numbers are formatted without country codes.</remarks> public static string GetDisplay(string phoneNumber) { if (string.IsNullOrWhiteSpace(phoneNumber)) { return(null); } PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumber p = phoneNumberUtil.Parse(phoneNumber, CountryCode); if (!phoneNumberUtil.IsValidNumber(p)) { return(null); } if (phoneNumberUtil.IsValidNumberForRegion(p, CountryCode)) { return(phoneNumberUtil.Format(p, PhoneNumberFormat.NATIONAL)); } return(phoneNumberUtil.Format(p, PhoneNumberFormat.INTERNATIONAL)); } catch (Exception) { return(null); } }
internal bool TryFormatPhone(string cellPhone, out string formattedPhone) { try { var phoneNumber = phoneNumberUtil.Parse(cellPhone, "ru"); formattedPhone = phoneNumberUtil.Format(phoneNumber, PhoneNumberFormat.INTERNATIONAL); return(true); } catch (NumberParseException) { formattedPhone = null; return(false); } }
public static string FormatNumberInternational(string number) { try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); PhoneNumber parsedNumber = util.Parse(number, null); return(util.Format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)); } catch (NumberParseException e) { Logger.LogError("FormatNumberInternational() failed: {0}\n{1}", e.Message, e.StackTrace); return(number); } }
public static String getInternationalFormatFromE164(String e164number) { try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); PhoneNumber parsedNumber = util.Parse(e164number, null); return(util.Format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)); } catch (NumberParseException e) { //Log.w(TAG, e); return(e164number); } }
public static string ToE164Number(this string src) { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.GetInstance(); string decodedNumber = null; try { var number = phoneNumberUtil.Parse(src, null); decodedNumber = phoneNumberUtil.Format(number, PhoneNumberFormat.E164); } catch (NumberParseException) { } return(decodedNumber); }
public ActionResult Index(DetailsModel model) { try { PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); PhoneNumber n = phoneUtil.Parse(model.Phone, "GB"); model.PhoneNumberFormatted = phoneUtil.Format(n, PhoneNumberFormat.INTERNATIONAL); } catch (Exception e) { ModelState.AddModelError("Phone", e.Message); } return(View(model)); }
private void FFMPEG(string name) { try { PhoneNumber nCheck = phoneUtil.Parse(name, "BR"); if (phoneUtil.IsValidNumber(nCheck)) { Console.WriteLine("Processando {0}", name); Process ffmpeg = new Process(); ProcessStartInfo oInfo = new ProcessStartInfo( @".\ffmpeg.exe", @"-i " + path + @"novos\" + name + @".mp4 -acodec copy -vcodec libx264 -b:v 1000k -an -f mp4 -y " + path + @"compactado\" + name + ".mp4"); oInfo.CreateNoWindow = true; oInfo.WindowStyle = ProcessWindowStyle.Hidden; ffmpeg.StartInfo = oInfo; ffmpeg.EnableRaisingEvents = true; ffmpeg.Exited += (s, o) => { string numberParsed = phoneUtil.Format(nCheck, PhoneNumberFormat.INTERNATIONAL); try { File.Move(path + @"compactado\" + name + @".mp4", path + @"completado\" + numberParsed + @".mp4"); File.Delete(path + @"novos\" + name + @".mp4"); } catch (IOException ex) { File.Delete(path + @"compactado\" + name + @".mp4"); File.Move(path + @"novos\" + name + @".mp4", path + @"errors\" + name + @"_" + new Random().Next() + @".mp4"); Console.WriteLine("Esse número ja teve uma mensagem enviada.\n {0}", ex.Message); } }; ffmpeg.Start(); } } catch (NumberParseException ex) { Console.WriteLine("Nome do arquivo não pode ser transformado em numero de telefone brasileiro!."); } }
public static bool TryParse(string phone, out InternationalPhone parsed) { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); try { PhoneNumber phoneNumber = util.Parse(phone, null); parsed = new InternationalPhone(util.Format(phoneNumber, PhoneNumberFormat.INTERNATIONAL)); return(true); } catch (NumberParseException) { parsed = null; return(false); } }
/// <summary> /// Helper method to get the national-number part of a number, formatted without any national /// prefix, and return it as a set of digit blocks that would be formatted together following /// standard formatting rules. /// </summary> private static IList <string> GetNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number) { // This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of // digits. var rfc3966Format = util.Format(number, PhoneNumberFormat.RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. var endIndex = rfc3966Format.IndexOf(';'); if (endIndex < 0) { endIndex = rfc3966Format.Length; } // The country-code will have a '-' following it. var startIndex = rfc3966Format.IndexOf('-') + 1; return(rfc3966Format.Substring(startIndex, endIndex - startIndex).Split('-')); }
/// <summary> /// Returns a phone number in E164 ISO format. /// </summary> /// <param name="phoneNumber">The phone number to format in E164 ISO format.</param> /// <returns>The phone number formatted in E164 ISO format. null is returned if the phone number is invalid.</returns> public static string GetE164(string phoneNumber) { if (string.IsNullOrWhiteSpace(phoneNumber)) { return(null); } PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.GetInstance(); try { PhoneNumber p = phoneNumberUtil.Parse(phoneNumber, CountryCode); if (!phoneNumberUtil.IsValidNumber(p)) { return(null); } return(phoneNumberUtil.Format(p, PhoneNumberFormat.E164)); } catch (Exception) { return(null); } }
/// <summary> /// Format to international phone number /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> public static string GetFormatedPhoneNumber(string phoneNumber) { PhoneNumber phone = null; PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance(); var temp = phoneNumber; try { temp = "+" + phoneNumber.Trim('+'); phone = phoneUtil.Parse(temp, "ZZ"); } catch (Exception ex)//if cannot format, will format to { temp = string.Format("+84{0}", phoneNumber); phone = phoneUtil.Parse(temp, "ZZ"); } return(phoneUtil.Format(phone, PhoneNumberFormat.E164)); }
private bool ValidatePhoneNumberAndCode() { if (string.IsNullOrEmpty(country_code)) { return(false); } PhoneNumberUtil phoneUtil = PhoneNumberUtil.Instance; Phonenumber.PhoneNumber phoneProto = null; try { phoneProto = phoneUtil.Parse(UserPhoneText.Text, country_code); } catch (NumberParseException npe) { Toast.MakeText(this, $"error: {npe.Message}", ToastLength.Short).Show(); } bool isValid = phoneUtil.IsValidNumber(phoneProto); if (isValid) { //international format var int_format = phoneUtil.Format(phoneProto, PhoneNumberUtil.PhoneNumberFormat.International); //normal format string phone = CCTV.Text + UserPhoneText.Text; SaveToSharedPreference(int_format, phoneProto.ToString()); Intent myintent = new Intent(this, typeof(PhoneValidationActivity)); StartActivity(myintent); OverridePendingTransition(Resource.Animation.slide_up_anim, Resource.Animation.slide_up_out); return(true); } else { helper.ShowCookieBar("Error", "Invalid phone number"); return(false); } }
public static string formatNumber(string number, string localNumber) //throws InvalidNumberException { if (number == null) { throw new InvalidNumberException("Null string passed as number."); } if (number.Contains("@")) { throw new InvalidNumberException("Possible attempt to use email address."); } number = number.ReplaceAll("[^0-9+]", ""); if (number.Length == 0) { throw new InvalidNumberException("No valid characters found."); } //if (number[0] == '+') // return number; try { PhoneNumberUtil util = PhoneNumberUtil.GetInstance(); PhoneNumber localNumberObject = util.Parse(localNumber, null); string localCountryCode = util.GetRegionCodeForNumber(localNumberObject); //Log.w(TAG, "Got local CC: " + localCountryCode); PhoneNumber numberObject = util.Parse(number, localCountryCode); return(util.Format(numberObject, PhoneNumberFormat.E164)); } catch (NumberParseException e) { //Log.w(TAG, e); return(impreciseFormatNumber(number, localNumber)); } }
/// <summary> /// Extracts the partial codes of the phone number /// </summary> /// <param name="numberModel">Google phone number representation to extract codes from</param> /// <param name="numberRepresentation">Intermediate representation containing the partial codes</param> private void GetPartialCodes(ref PhoneNumberModel numberModel, PhoneNumber numberRepresentation) { /*Format phonenumber to international representation*/ string internationalRep = phoneUtil.Format(numberRepresentation, PhoneNumberFormat.INTERNATIONAL); /*Parse out partial codes*/ string[] parts = internationalRep.Split(new char[0]); //split by whitespaces which represent the borders of partial codes within the international representation /*Initialize empty string for country code, local code and participant number*/ string[] partialCodes = new string[numberOfPartialCodes]; Array.Fill(partialCodes, string.Empty); parts.Take(numberOfPartialCodes).ToArray().CopyTo(partialCodes, 0); /*Extract partial codes from result array*/ numberModel.CountryCode = partialCodes[0].Remove(partialCodes[0].IndexOf('+'), 1); //Remove country code prefix(+) numberModel.AreaCode = partialCodes[1]; numberModel.ParticipantNumber = partialCodes[2]; /*Select ISO textual country representation corresponding the numeric country code*/ CountryCode codePicker = new CountryCode(); numberModel.ISOCountryText = codePicker.GetISOCode(numberModel.CountryCode); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string errorMessage = ""; string strValue = value as string; PhoneNumber phoneNum; if (isRequired) { if (string.IsNullOrEmpty(strValue)) { errorMessage = "شماره تلفن نمیتواند خالی باشد"; return(new ValidationResult(errorMessage)); } return(ValidationResult.Success); } try { phoneNum = phoneNumberUtil.Parse(strValue, region); } catch (Exception) { errorMessage = "فرمت شماره صحیح نیست"; return(new ValidationResult(errorMessage)); } if (!phoneNumberUtil.IsValidNumber(phoneNum)) { errorMessage = "فرمت شماره صحیح نیست"; return(new ValidationResult(errorMessage)); } validationContext.ObjectType.GetProperty(validationContext.MemberName) .SetValue(validationContext.ObjectInstance, phoneNumberUtil.Format(phoneNum, PhoneNumberFormat.INTERNATIONAL)); return(ValidationResult.Success); }
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]", "")); }