Example #1
0
 public override bool IsValid(object value)
 {
     if (value is string phoneNumber)
     {
         PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.GetInstance();
         CultureInfo     cultureInfo     = Thread.CurrentThread.CurrentCulture;
         RegionInfo      regionInfo      = new RegionInfo(cultureInfo.Name);
         PhoneNumber     phoneNumberObj  = phoneNumberUtil.Parse(phoneNumber, regionInfo.TwoLetterISORegionName);
         bool            result          = phoneNumberUtil.IsValidNumber(phoneNumberObj);
         if (result && (AcceptFixedNumbersOnly || AcceptMobileNumbersOnly))
         {
             PhoneNumberType numberType = phoneNumberUtil.GetNumberType(phoneNumberObj);
             if (AcceptFixedNumbersOnly)
             {
                 result = numberType == PhoneNumberType.FIXED_LINE || numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
             }
             else
             {
                 result = numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE || numberType == PhoneNumberType.MOBILE;
             }
         }
         return(result);
     }
     else
     {
         return(false);
     }
 }
 /**
  * @param exampleNumberRequestedType  type we are requesting an example number for
  * @param possibleExpectedTypes       acceptable types that this number should match, such as
  *     FIXED_LINE and FIXED_LINE_OR_MOBILE for a fixed line example number.
  */
 private void checkNumbersValidAndCorrectType(PhoneNumberType exampleNumberRequestedType,
                                              HashSet <PhoneNumberType> possibleExpectedTypes)
 {
     foreach (var regionCode in phoneNumberUtil.GetSupportedRegions())
     {
         PhoneNumber exampleNumber =
             phoneNumberUtil.GetExampleNumberForType(regionCode, exampleNumberRequestedType);
         if (exampleNumber != null)
         {
             if (!phoneNumberUtil.IsValidNumber(exampleNumber))
             {
                 invalidCases.Add(exampleNumber);
                 //LOGGER.log(Level.SEVERE, "Failed validation for " + exampleNumber.toString());
             }
             else
             {
                 // We know the number is valid, now we check the type.
                 PhoneNumberType exampleNumberType = phoneNumberUtil.GetNumberType(exampleNumber);
                 if (!possibleExpectedTypes.Contains(exampleNumberType))
                 {
                     wrongTypeCases.Add(exampleNumber);
                     //LOGGER.log(Level.SEVERE, "Wrong type for " + exampleNumber.toString() + ": got " + exampleNumberType);
                     //LOGGER.log(Level.WARNING, "Expected types: ");
                     //for (PhoneNumberType type : possibleExpectedTypes) {
                     //LOGGER.log(Level.WARNING, type.toString());
                 }
             }
         }
     }
 }
Example #3
0
        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");
                }
            }
        }
Example #4
0
        public bool IsMobilePhoneNumber(string phoneNumber)
        {
            try
            {
                var normalizedNumber = NormalizePhoneNumber(phoneNumber);
                var number           = _utils.Parse(normalizedNumber, "CH");
                var numberType       = _utils.GetNumberType(number);

                return(numberType == PhoneNumberType.MOBILE || numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
            }
            catch (NumberParseException)
            {
                return(false);
            }
        }
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            try
            {
                PhoneNumber phoneNumber = _phoneUtil.Parse(PhoneNumberCheck.PhoneNumberRaw, PhoneNumberCheck.CountryCodeSelected);

                var valid = _phoneUtil.IsValidNumberForRegion(phoneNumber, PhoneNumberCheck.CountryCodeSelected);
                Debug.Print($"{phoneNumber} is {valid} for region {PhoneNumberCheck.CountryCodeSelected}");

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.CountryCodeSelected)}").Value.RawValue =
                    PhoneNumberCheck.CountryCodeSelected;

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.PhoneNumberRaw)}").Value.RawValue =
                    PhoneNumberCheck.PhoneNumberRaw;

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.Valid)}").Value.RawValue =
                    _phoneUtil.IsValidNumberForRegion(phoneNumber, PhoneNumberCheck.CountryCodeSelected);

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.PhoneNumberType)}").Value.RawValue =
                    _phoneUtil.GetNumberType(phoneNumber);

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.RegionCode)}").Value.RawValue =
                    _phoneUtil.GetRegionCodeForNumber(phoneNumber);

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.PhoneNumberFormatted)}").Value.RawValue =
                    _phoneUtil.FormatOutOfCountryCallingNumber(phoneNumber, PhoneNumberCheck.CountryCodeSelected);

                ModelState.FirstOrDefault(x => x.Key == $"{nameof(PhoneNumberCheck)}.{nameof(PhoneNumberCheck.PhoneNumberMobileDialing)}").Value.RawValue =
                    _phoneUtil.FormatNumberForMobileDialing(phoneNumber, PhoneNumberCheck.CountryCodeSelected, true);

                return(Page());
            }
            catch (NumberParseException npex)
            {
                ModelState.AddModelError(npex.ErrorType.ToString(), npex.Message);
            }
            return(Page());
        }
Example #6
0
        /// <summary>
        /// Check if the Phone Number is valid and properly format it.
        /// </summary>
        /// <param name="phoneNumber">Source to parse.</param>
        /// <returns>Parsed result.</returns>
        public static ParsedPhoneNumber ParsePhoneNumber(string phoneNumber)
        {
            try
            {
                var parsed = PhoneNumberUtil.Parse(phoneNumber, RegionName);

                return(new ParsedPhoneNumber
                {
                    Normalized = $"{parsed.CountryCode}{parsed.NationalNumber}",
                    IsValid = PhoneNumberUtil.IsValidNumber(parsed),
                    IsMobile = PhoneNumberUtil.GetNumberType(parsed) == PhoneNumberType.MOBILE
                });
            }
            catch (NumberParseException)
            {
                return(new ParsedPhoneNumber
                {
                    IsValid = false
                });
            }
        }
Example #7
0
        /// <summary>
        /// Validate a mobile number from ulong source and ensure it is either MOBILE or FIXED_LINE_OR_MOBILE
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool IsValidMobileNumber(ulong mobile)
        {
            PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.GetInstance();
            string          e164PhoneNumber = $"+{mobile}";
            PhoneNumber     phoneNumber;

            try
            {
                phoneNumber = phoneNumberUtil.Parse(e164PhoneNumber, null);
            }
            catch
            {
                return(false);
            }

            PhoneNumberType type = phoneNumberUtil.GetNumberType(phoneNumber);

            if (type != PhoneNumberType.MOBILE && type != PhoneNumberType.FIXED_LINE_OR_MOBILE)
            {
                return(false);
            }

            return(true);
        }
Example #8
0
        public IActionResult Check(PhoneNumberCheckViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentException(nameof(model));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    PhoneNumber phoneNumber = _phoneUtil.Parse(model.PhoneNumberRaw, model.CountryCodeSelected);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.Valid)).Value.RawValue =
                        _phoneUtil.IsValidNumberForRegion(phoneNumber, model.CountryCodeSelected);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberType)).Value.RawValue =
                        _phoneUtil.GetNumberType(phoneNumber);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.CountryCode)).Value.RawValue =
                        _phoneUtil.GetRegionCodeForNumber(phoneNumber);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberFormatted)).Value.RawValue =
                        _phoneUtil.FormatOutOfCountryCallingNumber(phoneNumber, "US");
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberMobileDialing)).Value.RawValue =
                        _phoneUtil.FormatNumberForMobileDialing(phoneNumber, model.CountryCodeSelected, true);

                    ModelState.FirstOrDefault(x => x.Key == nameof(model.HasExtension)).Value.RawValue =
                        phoneNumber.HasExtension;

                    ModelState.FirstOrDefault(x => x.Key == nameof(model.CountryCodeSelected)).Value.RawValue =
                        model.CountryCodeSelected;
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberRaw)).Value.RawValue =
                        model.PhoneNumberRaw;

                    model.Countries = _countries.CountrySelectList;

                    return(View(model));
                }
                catch (NumberParseException npex)
                {
                    ModelState.AddModelError(npex.ErrorType.ToString(), npex.Message);
                }
            }

            model.Countries = _countries.CountrySelectList;

            ModelState.SetModelValue(nameof(model.CountryCodeSelected), model.CountryCodeSelected, model.CountryCodeSelected);
            ModelState.SetModelValue(nameof(model.PhoneNumberRaw), model.PhoneNumberRaw, model.PhoneNumberRaw);

            ModelState.SetModelValue(nameof(model.Valid), false, null);
            model.Valid = false;
            ModelState.SetModelValue(nameof(model.HasExtension), false, null);
            model.HasExtension = false;
            ModelState.SetModelValue(nameof(model.PhoneNumberType), null, null);
            model.PhoneNumberType = null;
            ModelState.SetModelValue(nameof(model.CountryCode), null, null);
            model.CountryCode = null;
            ModelState.SetModelValue(nameof(model.PhoneNumberFormatted), null, null);
            model.PhoneNumberFormatted = null;
            ModelState.SetModelValue(nameof(model.PhoneNumberMobileDialing), null, null);
            model.PhoneNumberMobileDialing = null;

            return(View(model));
        }
Example #9
0
        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);
            }
        }
Example #10
0
        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 bool IsMobileNumber(string number)
 {
     return(phoneNumberUtil.GetNumberType(phoneNumberUtil.Parse(number, null)) == PhoneNumberType.MOBILE);
 }
Example #12
0
        public IActionResult Check(PhoneNumberCheckViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Parse the number to check into a PhoneNumber object.
                    PhoneNumber phoneNumber = _phoneUtil.Parse(model.PhoneNumberRaw, model.CountryCodeSelected);

                    // Use the PhoneNumber object to get information from the utility and assign it to the raw state of the model.
                    // The values can't be assigned directly to the model because they have previously existing models.
                    // ASP.NET Core Tag Helpers work differently than Html Helpers in this respect (and others).
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.Valid)).Value.RawValue =
                        _phoneUtil.IsValidNumberForRegion(phoneNumber, model.CountryCodeSelected);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberType)).Value.RawValue =
                        _phoneUtil.GetNumberType(phoneNumber);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.CountryCode)).Value.RawValue =
                        _phoneUtil.GetRegionCodeForNumber(phoneNumber);
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberFormatted)).Value.RawValue =
                        _phoneUtil.FormatOutOfCountryCallingNumber(phoneNumber, "US");
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberMobileDialing)).Value.RawValue =
                        _phoneUtil.FormatNumberForMobileDialing(phoneNumber, model.CountryCodeSelected, true);

                    ModelState.FirstOrDefault(x => x.Key == nameof(model.HasExtension)).Value.RawValue =
                        phoneNumber.HasExtension;

                    // The submitted value has to be returned as the raw value.
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.CountryCodeSelected)).Value.RawValue =
                        model.CountryCodeSelected;
                    ModelState.FirstOrDefault(x => x.Key == nameof(model.PhoneNumberRaw)).Value.RawValue =
                        model.PhoneNumberRaw;

                    // Because the Countries property of the view model doesn't exist at this point (it's not passed back by
                    // the model binder when the form is submitted) it can be assigned directly before being returned to the view.
                    model.Countries = _countries.CountrySelectList;

                    return(View(model));
                }
                catch (NumberParseException npex)
                {
                    // If PhoneNumberUtil throws an error, add it to the list of ModelState errors.
                    // This will change ModelState.IsValid to false.
                    ModelState.AddModelError(npex.ErrorType.ToString(), npex.Message);
                }
            }

            // If there is an unspecified ModelState error or a NumberParseException
            // repopulate the list of countries, selected country, and attempted phone number.
            // Clear the values of the results in both the ModelState values and the model.
            // Doing both is required by MVC handling of Tag Helpers. For Html Helpers, only
            // the model values need to be reset.
            // In production code, the results section would best be implemented with a partial
            // page with its own view model, which could then be reinitialized for each new
            // attempt. It's handled this way to keep the focus on the library functionality.

            model.Countries = _countries.CountrySelectList;

            ModelState.SetModelValue(nameof(model.CountryCodeSelected), model.CountryCodeSelected, model.CountryCodeSelected);
            ModelState.SetModelValue(nameof(model.PhoneNumberRaw), model.PhoneNumberRaw, model.PhoneNumberRaw);

            ModelState.SetModelValue(nameof(model.Valid), false, null);
            model.Valid = false;
            ModelState.SetModelValue(nameof(model.HasExtension), false, null);
            model.HasExtension = false;
            ModelState.SetModelValue(nameof(model.PhoneNumberType), null, null);
            model.PhoneNumberType = null;
            ModelState.SetModelValue(nameof(model.CountryCode), null, null);
            model.CountryCode = null;
            ModelState.SetModelValue(nameof(model.PhoneNumberFormatted), null, null);
            model.PhoneNumberFormatted = null;
            ModelState.SetModelValue(nameof(model.PhoneNumberMobileDialing), null, null);
            model.PhoneNumberMobileDialing = null;

            return(View(model));
        }
Example #13
0
        private void ValidateMobilePhoneNumber(string mobilePhoneNumber)
        {
            PhoneNumberUtil  instance = PhoneNumberUtil.GetInstance();
            HashSet <string> validSupportedRegions = this.supportedValidationRegions
                                                     .Join(
                instance.GetSupportedRegions(),
                s => s,
                r => r,
                (s, r) => s)
                                                     .OrderBy(code => code)
                                                     .ToHashSet();

            bool validPhoneNumber = false;

            foreach (string region in validSupportedRegions)
            {
                try
                {
                    PhoneNumber phoneNumber = instance.Parse(mobilePhoneNumber, region);
                    if (instance.GetNumberType(phoneNumber) != PhoneNumberType.MOBILE)
                    {
                        continue;
                    }

                    validPhoneNumber = true;
                    break;
                }
                catch (NumberParseException)
                {
                }
            }

            if (validPhoneNumber)
            {
                return;
            }

            StringBuilder errorMessage = new StringBuilder();

            errorMessage.AppendLine("Invalid mobile phone number.");
            errorMessage.AppendLine("Examples :");
            foreach (string region in validSupportedRegions)
            {
                PhoneNumber example = instance.GetExampleNumberForType(region, PhoneNumberType.MOBILE);

                StringBuilder formattedExample = new StringBuilder();

                if (example.NumberOfLeadingZeros > 0)
                {
                    formattedExample.Append("(");
                    for (int i = 0; i < example.NumberOfLeadingZeros; i++)
                    {
                        formattedExample.Append("0");
                    }

                    formattedExample.Append(")");
                }

                formattedExample.Append(example.NationalNumber);

                errorMessage.AppendLine($"\t{region} : {formattedExample}");
            }

            throw new ApplicationException(errorMessage.ToString());
        }