Python phonenumbers.NumberParseException() Examples

The following are 19 code examples of phonenumbers.NumberParseException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module phonenumbers , or try the search function .
Example #1
Source File: customer.py    From Servo with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def clean(self):
        cd = super(CustomerForm, self).clean()

        phone = cd.get('phone')
        country = cd.get('country')

        if len(phone) < 1:
            return cd

        try:
            phonenumbers.parse(phone, country)
        except phonenumbers.NumberParseException:
            msg = _('Enter a valid phone number')
            self._errors["phone"] = self.error_class([msg])

        return cd 
Example #2
Source File: models.py    From casepro with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def validate_phone(cls, number):
        """
        Validates the given phone number which should be in E164 format.
        """
        try:
            parsed = phonenumbers.parse(number)
        except phonenumbers.NumberParseException as e:
            raise InvalidURN(str(e))

        if number != phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164):
            raise InvalidURN("Phone numbers must be in E164 format")

        if not phonenumbers.is_possible_number(parsed) or not phonenumbers.is_valid_number(parsed):
            raise InvalidURN("Phone numbers must be in E164 format")

        return True 
Example #3
Source File: forms.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 6 votes vote down vote up
def clean(self):
        data = self.cleaned_data

        phone_number = (data['phone_country_code'] or '') + \
            (data['phone_number'] or '')

        if data['phone_country_code'] and data['phone_number']:
            phone_number = data['phone_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 phonenumbers.NumberParseException as e:
                self.add_error('phone_number', e)

        if data['pushbullet_access_token']:
            pushbullet_access_token = data['pushbullet_access_token']
            try:
                Pushbullet(pushbullet_access_token)
            except PushbulletError:
                self.add_error('pushbullet_access_token',
                               'Invalid pushbullet access token.')

        data['telegram_chat_id'] = data['telegram_chat_id'] if data['telegram_chat_id'] else None 
Example #4
Source File: dedupe.py    From lieu with MIT License 6 votes vote down vote up
def normalized_phone_numbers(cls, a1, a2):
        num1 = a1.get(EntityDetails.PHONE, u'').strip()
        num2 = a2.get(EntityDetails.PHONE, u'').strip()

        country_code1 = a1.get(AddressComponents.COUNTRY)
        country_code2 = a2.get(AddressComponents.COUNTRY)

        if country_code1 and country_code2 and country_code1 != country_code2:
            return None, None

        country_code = country_code1 or country_code2

        try:
            p1 = phonenumbers.parse(num1, region=country_code)
            p2 = phonenumbers.parse(num2, region=country_code)
        except phonenumbers.NumberParseException:
            return None, None

        return p1, p2 
Example #5
Source File: widgets.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def clean_international_phonenumber(value):
    """
    Validate phone number taken from TelPrefixInput and return in format suitable for our DB.
    """
    invalid_number_message = _(u'The phone number entered is not valid.')

    try:
        num = phonenumbers.parse(value)
        if not phonenumbers.is_valid_number(num):
            raise forms.ValidationError(invalid_number_message)
    except phonenumbers.NumberParseException:
        raise forms.ValidationError(invalid_number_message)

    return phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.E164)


# noinspection PyAbstractClass 
Example #6
Source File: __init__.py    From travelcrm with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, node, value):
        try:
            phone = phonenumbers.parse(value)
        except phonenumbers.NumberParseException:
            raise colander.Invalid(
                node,
                _(
                    u"Phone must be in format +XXXXXXXXXXX "
                    u"and contains country code",
                    mapping={'val': value}
                )
            )
        if not phonenumbers.is_valid_number(phone):
            raise colander.Invalid(
                node,
                _(
                    u"Phone is not valid",
                    mapping={'val': value}
                )
            ) 
Example #7
Source File: utils.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_python(value):
    if value in (None, ""):  # None or ''
        phone_number = value
    elif value and isinstance(value, str):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except phonenumbers.NumberParseException:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
    elif isinstance(value, phonenumbers.PhoneNumber) and not isinstance(
        value, PhoneNumber
    ):
        phone_number = PhoneNumber()
        phone_number.merge_from(value)
    elif isinstance(value, PhoneNumber):
        phone_number = value
    else:
        # TODO: this should somehow show that it has invalid data, but not
        #       completely die for bad data in the database.
        #       (Same for the NumberParseException above)
        phone_number = None
    return phone_number 
Example #8
Source File: utils.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __eq__(self, other):
        """
        Override parent equality because we store only string representation
        of phone number, so we must compare only this string representation
        """
        if (
            isinstance(other, PhoneNumber)
            or isinstance(other, phonenumbers.PhoneNumber)
            or isinstance(other, str)
        ):
            format_string = "E164"
            default_region = None
            fmt = self.format_map[format_string]
            if isinstance(other, str):
                # convert string to phonenumbers.PhoneNumber
                # instance
                try:
                    other = phonenumbers.parse(other, region=default_region)
                except phonenumbers.NumberParseException:
                    # Conversion is not possible, thus not equal
                    return False
            other_string = phonenumbers.format_number(other, fmt)
            return self.format_as(fmt) == other_string
        else:
            return False 
Example #9
Source File: forms.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_phone(self):
        phone = self.data.get('phone')
        if phone:
            if VerificationDevice.objects.filter(
                    unverified_phone=phone).exists():
                raise forms.ValidationError(
                    _("User with this Phone number already exists."))
            try:
                parse_phone(phone)
            except NumberParseException:
                raise forms.ValidationError(
                    _("Please enter a valid country code."))
        else:
            phone = None
        return phone 
Example #10
Source File: forms.py    From account-security-quickstart-django with MIT License 5 votes vote down vote up
def clean(self):
        data = self.cleaned_data
        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) 
Example #11
Source File: address.py    From correios with Apache License 2.0 5 votes vote down vote up
def __init__(self, number: str, country="BR") -> None:
        try:
            self.parsed = self._parse(number, country)
        except NumberParseException:
            self.parsed = None
        self.country = country
        self.number = "".join(d for d in number if d.isdigit()) 
Example #12
Source File: forms.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_password(self):
        password = self.data.get('password')
        validate_password(password)
        errors = []

        email = self.data.get('email')
        if email:
            email = email.split('@')
            if email[0].casefold() in password.casefold():
                errors.append(_("Passwords cannot contain your email."))

        username = self.data.get('username')
        if len(username) and username.casefold() in password.casefold():
            errors.append(
                _("The password is too similar to the username."))

        phone = self.data.get('phone')
        if phone and phone_validator(phone):
            try:
                phone = str(parse_phone(phone).national_number)
                if phone in password:
                    errors.append(_("Passwords cannot contain your phone."))
            except NumberParseException:
                pass

        if errors:
            raise forms.ValidationError(errors)

        return password 
Example #13
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_phone(self, phone):
        instance = self.instance
        if (instance and phone != instance.phone and
                self.context['request'].user != instance):
            raise serializers.ValidationError(_("Cannot update phone"))

        if instance and instance.phone == phone:
            return phone

        if phone:
            # make sure that the new phone updated by a user is not a duplicate
            # of an unverified phone already linked to a different user
            if VerificationDevice.objects.filter(
                    unverified_phone=phone).exists():
                raise serializers.ValidationError(
                    _("User with this Phone number already exists."))
            try:
                parse_phone(phone)
            except NumberParseException:
                raise serializers.ValidationError(
                    _("Please enter a valid country code."))
        else:
            phone = None

            if (instance and instance.phone and
                    not instance.email and self.initial_data.get('email')):
                raise serializers.ValidationError(
                    _('It is not possible to change from phone to email for '
                      'your account identifier.'))
        return phone 
Example #14
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_phone(self, phone):
        if phone:
            if VerificationDevice.objects.filter(
                    unverified_phone=phone).exists():
                raise serializers.ValidationError(
                    _("User with this Phone number already exists."))
            try:
                parse_phone(phone)
            except NumberParseException:
                raise serializers.ValidationError(
                    _("Please enter a valid country code."))
        else:
            phone = None

        return phone 
Example #15
Source File: forms.py    From conducthotline.com with Apache License 2.0 5 votes vote down vote up
def validate_phone_number(form, field):
    try:
        number = phonenumbers.parse(field.data, "US")

    except phonenumbers.NumberParseException:
        raise wtforms.ValidationError(
            f"{field.data} does not appear to be a valid number."
        )

    if not phonenumbers.is_possible_number(number):
        raise wtforms.ValidationError(
            f"{field.data} does not appear to be a possible number."
        )

    field.data = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) 
Example #16
Source File: app.py    From conducthotline.com with Apache License 2.0 5 votes vote down vote up
def phone_format_filter(s):
    try:
        number = phonenumbers.parse(s, "US")
        return phonenumbers.format_number(
            number, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )
    except phonenumbers.NumberParseException:
        return s 
Example #17
Source File: validators.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def phone_validator(val):
    try:
        phonenumbers.parse(val, settings.INSTALL_COUNTRY)
    except phonenumbers.NumberParseException:
        raise ValidationError(_('%s is not a valid phone number') % val) 
Example #18
Source File: smsaction.py    From VizAlerts with MIT License 4 votes vote down vote up
def smsnumber_to_e164(smsnumber, iso2countrycode):
    """Tries to convert a string into an E.164 formatted phone number
       Raises exception if it can't, returns the E.164 number as a string, if it can """

    try:
        log.logger.debug(u'Converting {} to E.164 format, country code {}'.format(smsnumber, iso2countrycode))

        try:
            if smsnumber.startswith('+'):
                smsnumber_obj = phonenumbers.parse(smsnumber)
            else:
                # country code not specified in number, so pass it in
                smsnumber_obj = phonenumbers.parse(smsnumber, iso2countrycode)
        except phonenumbers.NumberParseException as e:
            errormessage = u'SMS Unable to parse number {}. Error: {}'.format(smsnumber, e.message)
            log.logger.error(errormessage)
            raise UserWarning(errormessage)

        try:
            if not phonenumbers.is_possible_number(smsnumber_obj):
                errormessage = u'SMS Number is not possibly valid: {}.'.format(smsnumber)
                log.logger.error(errormessage)
                raise UserWarning(errormessage)
        except phonenumbers.NumberParseException as e:
            errormessage = u'SMS Unable to parse number {}. Error: {}'.format(smsnumber, e.message)
            log.logger.error(errormessage)
            raise UserWarning(errormessage)

        if not phonenumbers.is_valid_number(smsnumber_obj):
            errormessage = u'SMS Number is not valid: {}.'.format(smsnumber)
            log.logger.error(errormessage)
            raise UserWarning(errormessage)


        e164_number = phonenumbers.format_number(smsnumber_obj, phonenumbers.PhoneNumberFormat.E164)
        if not e164_number:
            errormessage = u'SMS number {} could not be converted to E.164 for an unknown reason.'.format(smsnumber)
            log.logger.error(errormessage)
            raise UserWarning(errormessage)

        # all good, return it!
        return e164_number
    except Exception as e:
        log.logger.error(e.message)
        return None 
Example #19
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
def validate_password(self, password):
        validate_password(password)

        errors = []
        email = self.initial_data.get('email')
        if email:
            email = email.split('@')
            if email[0].casefold() in password.casefold():
                errors.append(_("Passwords cannot contain your email."))

        username = self.initial_data.get('username')
        if len(username) and username.casefold() in password.casefold():
            errors.append(
                _("The password is too similar to the username."))

        phone = self.initial_data.get('phone')
        if phone:
            if phone_validator(phone):
                try:
                    phone = str(parse_phone(phone).national_number)
                    if phone in password:
                        errors.append(
                            _("Passwords cannot contain your phone."))
                except NumberParseException:
                    pass
        if errors:
            raise serializers.ValidationError(errors)

        return password