Пример #1
0
        public bool GetISDCode(string PhoneNum)
        {
            // string number = "+919769321013";
            PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();

            try
            {
                PhoneNumber numberProto = phoneUtil.Parse(PhoneNum, "");
                // System.out.println("Number is of region - "
                string region = phoneUtil.GetRegionCodeForNumber(numberProto);
                isValid = (phoneUtil.IsValidNumber(numberProto) == true ? "Yes" : "No");
            }
            catch (NumberParseException e)
            {
                string error = "NumberParseException was thrown: "
                               + e.ToString();
                //Teetra.Helpers.ConstantVar.PhoneNumError = e.Message;
                return(false);
            }
            if (isValid == "Yes")
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #2
0
        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);
        }
Пример #3
0
        /// <summary>
        /// Parsed the number submitted as string
        /// </summary>
        /// <param name="number">The number to parse</param>
        /// <returns>An instance of type <see cref="NumberData"/> containing all the information about the number</returns>
        /// <exception cref="NumberParseException">Thrown when the number to be parsed is not a phone number</exception>
        public NumberData ParsePhoneNumber(string number)
        {
            // Get an instance of the parser and declare a PhoneNumber result variable
            PhoneNumberUtil numberParser = PhoneNumberUtil.GetInstance();
            PhoneNumber     parsedNumber;

            // Try to parse the variable with default region Germany
            try
            {
                parsedNumber = numberParser.Parse(number, "DE");
            }
            catch (NumberParseException)
            {
                throw;
            }

            // Check if the number is valid
            if (!numberParser.IsValidNumber(parsedNumber))
            {
                throw new ArgumentException("Invalid number");
            }

            // Gets the region code for the number such as "DE" for germany
            string regionCode = numberParser.GetRegionCodeForNumber(parsedNumber);

            // Extract the area code from the number
            string areaCode = GetAreaCode(numberParser, parsedNumber, number);

            // Extract the subscriber number
            string subscriberNumber = GetSubscriberNumber(numberParser, parsedNumber);

            // Extract the extension if available
            string extension = parsedNumber.HasExtension ? parsedNumber.Extension : string.Empty;

            // Build the clear number
            string clearNumber = GetClearNumber(number);

            // Build the iso normed number format
            string countryCode = parsedNumber.CountryCode.ToString();
            string isoNormed   = GetIsoNormedNumber(countryCode, areaCode, subscriberNumber, extension);

            // Fill the NumberData object to be returned
            NumberData numberData = new NumberData
            {
                CountryCode      = regionCode,
                AreaCode         = areaCode,
                SubscriberNumber = subscriberNumber,
                Extension        = extension,
                DigitString      = clearNumber,
                ISONormedNumber  = isoNormed,
            };

            return(numberData);
        }
        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());
        }
Пример #5
0
        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));
            }
        }
Пример #6
0
        /**
         * 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)
        {
            var regionCode = phoneUtil.GetRegionCodeForNumber(number);

            return(GetRegionDisplayName(regionCode, language));
        }
Пример #7
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));
        }
Пример #8
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);
            }
        }
Пример #9
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);
            }
        }
Пример #10
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));
        }