Python phonenumbers.is_valid_number() Examples

The following are 17 code examples of phonenumbers.is_valid_number(). 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: phone_util.py    From flask-security with MIT License 7 votes vote down vote up
def get_canonical_form(self, input_data):
        """ Validate and return a canonical form to be stored in DB
        and compared against.
        Returns ``None`` if input isn't a valid phone number.
        """
        import phonenumbers

        try:
            z = phonenumbers.parse(
                input_data, region=config_value("PHONE_REGION_DEFAULT")
            )
            if phonenumbers.is_valid_number(z):
                return phonenumbers.format_number(
                    z, phonenumbers.PhoneNumberFormat.E164
                )
            return None
        except phonenumbers.phonenumberutil.NumberParseException:
            return None 
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: functions.py    From docassemble with MIT License 6 votes vote down vote up
def phone_number_is_valid(number, country=None):
    """Given a phone number and a country code, returns True if the phone number is valid, otherwise False."""
    ensure_definition(number, country)
    if country is None:
        country = get_country()
    if isinstance(number, str):
        m = re.search(r'^whatsapp:(.*)', number)
        if m:
            number = m.group(1)
    try:
        pn = phonenumbers.parse(number, country)
    except:
        return False
    if phonenumbers.is_possible_number(pn) and phonenumbers.is_valid_number(pn):
        return True
    return False 
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: writers.py    From micromasters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #7
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 #8
Source File: utils.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_valid(self):
        """
        checks whether the number supplied is actually valid
        """
        return phonenumbers.is_valid_number(self) 
Example #9
Source File: field_types.py    From intake with MIT License 5 votes vote down vote up
def parse_phone_number(self, raw_string=None, country="US"):
        raw_string = raw_string or self.get_current_value()
        if raw_string:
            parsed_num = phonenumbers.parse(raw_string, country)
            if not phonenumbers.is_valid_number(parsed_num):
                raise exceptions.InvalidPhoneNumberException(
                    "'{}' is not a valid phone number".format(raw_string))
            return parsed_num
        return self.empty_value 
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
        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) 
Example #11
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 #12
Source File: utils.py    From momoapi-python with MIT License 5 votes vote down vote up
def validate_phone_number(number):
    obj = phonenumbers.parse(number, "UG")
    if not phonenumbers.is_valid_number(obj):
        raise ValidationError("Invalid Phone number {0}".format(number))
    if (carrier.name_for_number(obj, "en") != "MTN"):
        raise ValidationError(
            "{0}: Only MTN is supported at the moment".format(number))
    return "256{0}".format(obj.national_number) 
Example #13
Source File: phoneinfoga.py    From Phoneinfoga with GNU General Public License v3.0 5 votes vote down vote up
def localScan(InputNumber):
    global number
    global localNumber
    global internationalNumber
    global numberCountryCode
    global numberCountry

    print(code_info + 'Running local scan...')

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except:
        return False
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]

        countryRequest = json.loads(requests.request('GET', 'https://restcountries.eu/rest/v2/callingcode/{}'.format(numberCountryCode.replace('+', ''))).content)
        numberCountry = countryRequest[0]['alpha2Code']

        localNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        print(code_result + 'International format: {}'.format(internationalNumber))
        print(code_result + 'Local format: 0{}'.format(localNumber))
        print(code_result + 'Country code: {}'.format(numberCountryCode))
        print(code_result + 'Location: {}'.format(geocoder.description_for_number(PhoneNumberObject, "en")))
        print(code_result + 'Carrier: {}'.format(carrier.name_for_number(PhoneNumberObject, 'en')))
        print(code_result + 'Area: {}'.format(geocoder.description_for_number(PhoneNumberObject, 'en')))
        for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
            print(code_result + 'Timezone: {}'.format(timezoneResult))

        if phonenumbers.is_possible_number(PhoneNumberObject):
            print(code_info + 'The number is valid and possible.')
        else:
            print(code_warning + 'The number is valid but might not be possible.') 
Example #14
Source File: phone_util.py    From flask-security with MIT License 5 votes vote down vote up
def validate_phone_number(self, input_data):
        """ Return ``None`` if a valid phone number else an error message. """
        import phonenumbers

        try:
            z = phonenumbers.parse(
                input_data, region=config_value("PHONE_REGION_DEFAULT")
            )
            if phonenumbers.is_valid_number(z):
                return None
        except phonenumbers.phonenumberutil.NumberParseException:
            pass
        return get_message("PHONE_INVALID")[0] 
Example #15
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 #16
Source File: localscan.py    From phonia with MIT License 4 votes vote down vote up
def scan(InputNumber, print_results=True):
    test('Running local scan...')

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        throw(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode))

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, 'en')

        if print_results:
            info('International format: {}'.format(internationalNumber))
            info('Local format: {}'.format(localNumber))
            info('Country found: {} ({})'.format(country, numberCountryCode))
            info('City/Area: {}'.format(location))
            info('Carrier: {}'.format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
                info('Timezone: {}'.format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                plus('The number is valid and possible!')
            else:
                warn('The number is valid but might not be possible.')

    numberObj = {}
    numberObj['input'] = InputNumber
    numberObj['default'] = number
    numberObj['local'] = localNumber
    numberObj['international'] = internationalNumber
    numberObj['country'] = country
    numberObj['countryCode'] = numberCountryCode
    numberObj['countryIsoCode'] = numberCountry
    numberObj['location'] = location
    numberObj['carrier'] = carrierName

    return numberObj 
Example #17
Source File: target_info.py    From whatsapp-play with MIT License 4 votes vote down vote up
def localScan(InputNumber, print_results=True):
    print("Running local scan...")

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        print(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace("+", "")
        numberCountryCode = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(" ")[0]
        numberCountry = phonenumbers.region_code_for_country_code(int(numberCountryCode))

        localNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(numberCountryCode, "")
        internationalNumber = phonenumbers.format_number(PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, "en")

        if print_results:
            print("International format: {}".format(internationalNumber))
            print("Local format: {}".format(localNumber))
            print("Country found: {} ({})".format(country, numberCountryCode))
            print("City/Area: {}".format(location))
            print("Carrier: {}".format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
                print("Timezone: {}".format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                print("The number is valid and possible.")
            else:
                print("The number is valid but might not be possible.")

    numberObj = {}
    numberObj["input"] = InputNumber
    numberObj["default"] = number
    numberObj["local"] = localNumber
    numberObj["international"] = internationalNumber
    numberObj["country"] = country
    numberObj["countryCode"] = numberCountryCode
    numberObj["countryIsoCode"] = numberCountry
    numberObj["location"] = location
    numberObj["carrier"] = carrierName

    return numberObj