How to use the phonenumbers.phonenumberutil.NumberParseException function in phonenumbers

To help you get started, we’ve selected a few phonenumbers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github django-oscar / django-oscar / src / oscar / core / phonenumber.py View on Github external
def to_python(value):
    if value in validators.EMPTY_VALUES:  # None or ''
        phone_number = None
    elif value and isinstance(value, six.string_types):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except phonenumbers.phonenumberutil.NumberParseException:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
    elif isinstance(value, PhoneNumber):
        phone_number = value
    return phone_number
github django-oscar / django-oscar / oscar / core / phonenumber.py View on Github external
def to_python(value):
    if value in validators.EMPTY_VALUES:  # None or ''
        phone_number = None
    elif value and isinstance(value, six.string_types):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except phonenumbers.phonenumberutil.NumberParseException:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
    elif isinstance(value, PhoneNumber):
        phone_number = value
    return phone_number
github mitodl / micromasters / exams / pearson / writers.py View on Github external
def _parse_phone_number(cls, phone_number_string):
        """
        Parses a phone number string and raises proper exceptions in case it is invalid

        Args:
            phone_number_string (str): a string representing a phone number

        Returns:
            phonenumbers.phonenumber.PhoneNumber: a PhoneNumber object
        """
        try:
            phone_number = phonenumbers.parse(phone_number_string)
        except phonenumbers.phonenumberutil.NumberParseException:
            raise InvalidProfileDataException('Stored phone number is in an invalid string')
        if not phonenumbers.is_valid_number(phone_number):
            raise InvalidProfileDataException('Stored phone number is in an invalid phone number')
        return phone_number
github TwilioDevEd / account-security-quickstart-django / twofa / forms.py View on Github external
def clean(self):
        data = self.cleaned_data
        if data['password'] != data['confirm_password']:
            self.add_error(
                'password',
                'Password and confirmation did not match'
            )

        phone_number = data['country_code'] + data['phone_number']
        try:
            phone_number = phonenumbers.parse(phone_number, None)
            if not phonenumbers.is_valid_number(phone_number):
                self.add_error('phone_number', 'Invalid phone number')
        except NumberParseException as e:
            self.add_error('phone_number', e)
github kvesteri / wtforms-components / wtforms_components / fields / phone_number.py View on Github external
def process_formdata(self, valuelist):
        import phonenumbers

        if valuelist:
            if valuelist[0] == u'':
                self.data = None
            else:
                try:
                    self.data = PhoneNumber(
                        valuelist[0],
                        self.country_code
                    )
                    if not self.data.is_valid_number():
                        self.data = None
                        raise ValueError(self.gettext(self.error_msg))
                except phonenumbers.phonenumberutil.NumberParseException:
                    self.data = None
                    raise ValueError(self.gettext(self.error_msg))
github CroceRossaItaliana / jorvik / anagrafica / models.py View on Github external
def aggiungi_numero_telefono(self, numero, servizio=False, paese="IT"):
        """
        Aggiunge un numero di telefono per la persona.
        :param numero: Il numero di telefono.
        :param servizio: Vero se il numero e' di servizio. Default False.
        :param paese: Suggerimento per il paese. Default "IT".
        :return: True se l'inserimento funziona, False se il numero e' mal formattato.
        """
        try:
            n = phonenumbers.parse(numero, paese)
        except phonenumbers.phonenumberutil.NumberParseException:
            return False
        f = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
        t = Telefono(persona=self, numero=f, servizio=servizio)
        try:
            t.save()
        except:
            return False
        return True
github HealthByRo / universal_notifications / universal_notifications / backends / sms / abstract.py View on Github external
def validate_mobile(self, value):
        """Validate if number is mobile

        Arguments:
            value {string|phonenumbers.PhoneNumber} -- phone number

        Returns:
            bool -- return True if number is mobile
        """
        if not settings.UNIVERSAL_NOTIFICATIONS_VALIDATE_MOBILE:
            return True

        if not isinstance(value, phonenumbers.PhoneNumber):
            try:
                value = phonenumbers.parse(value, 'US')
            except phonenumbers.phonenumberutil.NumberParseException:
                return False
        return value
github codeforamerica / intake / formation / field_types.py View on Github external
stripping them of leading and trailing whitespace
        """
        value = self.empty_value
        if raw_value is not UNSET:
            self.assert_parse_received_correct_type(raw_value, str)
            raw_value = self.parse_as_text(raw_value)
        if raw_value:
            digits_only = extract_digit_chars(raw_value)
            if not digits_only:
                self.add_error(
                    self.parse_error_message.format(raw_value))
            else:
                try:
                    value = str(
                        self.parse_phone_number(digits_only).national_number)
                except (NumberParseException,
                        exceptions.InvalidPhoneNumberException) as error:
                    if not self.skip_validation_parse_only:
                        self.add_error(
                            self.parse_error_message.format(raw_value))
        return value
github odoo / odoo / addons / phone_validation / tools / phone_validation.py View on Github external
def phone_parse(number, country_code):
        try:
            phone_nbr = phonenumbers.parse(number, region=country_code, keep_raw_input=True)
        except phonenumbers.phonenumberutil.NumberParseException as e:
            raise UserError(_('Unable to parse %s: %s') % (number, str(e)))

        if not phonenumbers.is_possible_number(phone_nbr):
            raise UserError(_('Impossible number %s: probably invalid number of digits') % number)
        if not phonenumbers.is_valid_number(phone_nbr):
            raise UserError(_('Invalid number %s: probably incorrect prefix') % number)

        return phone_nbr
github Sotera / pst-extraction / spark / phone_numbers.py View on Github external
# the phone number string with "+" for parse() to work properly. If the number can't
            # be parsed it will throw a NumberParseException.
            phone_number_obj = phonenumbers.parse(u'+'+value_normalized, None)

            # More lenient than valid_num
            possible_num = phonenumbers.is_possible_number(phone_number_obj)
            valid_num= phonenumbers.is_valid_number(phone_number_obj)

            # print "possible=%s valid=%s"%(str(possible_num), str(valid_num))
            # If the phonenumbers module thinks the number is invalid BUT it is preceded by text
            # with a phone-related keyword, we'll accept the number. If the number is invalid and
            # doesn't have a phone-related keyword, however, skip it.
            if (not possible_num or not valid_num) and not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        except phonenumbers.phonenumberutil.NumberParseException as err:

            # The phonenumbers modules couldn't parse the number; however, if it's preceded by text
            # with a phone-related keyword we'll still accept it. Or put another way, if it is NOT
            # preceded by a phone keyword, skip it.
            if not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        #There seems to be a bug with some strings that cause partial numbers to be returned
        if len(value_normalized) < 7:
            continue

        # If we got this far, it means we're accepting the number as a phone number. Extract a snippet
        # of text that follows the match.
        excerpt_stop = match.end() + EXCERPT_CHAR_BUFFER
        if excerpt_stop > len(source_txt):
            excerpt_stop = len(source_txt)