How to use the phonenumbers.is_possible_number 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 HackNC / hacknotify / hacknotify / notify.py View on Github external
def do_number_parse(numlist):
    """
    Preprocess the list making sure formatting is correct
    Return a valid list
    """
    invalid_list = []
    valid_list = []
    
    for number in numlist:
        
        try:
            
            possible_number = number[0]
            parsed_number = phonenumbers.parse(possible_number, config.DEFAULT_REGION)
            
            if phonenumbers.is_possible_number(parsed_number):
                unicode_number = phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
                unicode_number = unicode_number.replace(' ', '') # remove the spaces
                unicode_number = unicode_number.replace('+', '') # remove the +
                unicode_number = unicode_number.replace('-', '') # remove the -
                valid_list.append(unicode_number)
            else:
                invalid_list.append(number)
        
        except IndexError:
            invalid_list.append(number)

    return valid_list
github theacodes / conducthotline.com / hotline / events / forms.py View on Github external
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)
github Sotera / pst-extraction / spark / numbers_extractor.py View on Github external
excerpt_start = match.start() - EXCERPT_CHAR_BUFFER
        if excerpt_start < 0:
            excerpt_start = 0
        excerpt_prefix = source_txt[ excerpt_start : match.start() ]

        phone_number_obj = None

        try:
            # print "phone guess: %s"%value_normalized
            # Try using the 'phonenumbers' module to parse the number. Note that we need to prefix
            # 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
github govau / notify / utils / notifications_utils / recipients.py View on Github external
def postvalidate_phone_number(number):
    if not phonenumbers.is_possible_number(number):
        reason = phonenumbers.is_possible_number_with_reason(number)

        if f'{number.country_code}' not in COUNTRY_PREFIXES:
            raise InvalidPhoneError('Not a valid country prefix')

        if reason == phonenumbers.ValidationResult.INVALID_COUNTRY_CODE:
            raise InvalidPhoneError('Not a valid country prefix')

        if reason == phonenumbers.ValidationResult.TOO_SHORT:
            raise InvalidPhoneError('Not enough digits')

        if reason == phonenumbers.ValidationResult.TOO_LONG:
            raise InvalidPhoneError('Too many digits')

        if reason == phonenumbers.ValidationResult.INVALID_LENGTH:
            raise InvalidPhoneError('Wrong amount of digits')
github alephdata / aleph / aleph / data / parse.py View on Github external
"""Parse a phone number and return in international format.

    If no valid phone number can be detected, None is returned. If
    a country code is supplied, this will be used to infer the
    prefix.

    https://github.com/daviddrysdale/python-phonenumbers
    """
    number = stringify(number)
    if number is None:
        return
    if country is not None:
        country = country.upper()
    try:
        num = phonenumbers.parse(number, country)
        if phonenumbers.is_possible_number(num):
            if phonenumbers.is_valid_number(num):
                num = phonenumbers.format_number(num, PHONE_FORMAT)
                return num.replace(' ', '')
        return
    except NumberParseException:
        return
github uw-it-aca / spotseeker_server / spotseeker_server / org_forms / uw_spot.py View on Github external
cleaned_data = super(UWSpotExtendedInfoForm, self).clean()
        # Have to check value here since we look at multiple items
        key = self.cleaned_data['key']
        value = self.cleaned_data['value']

        if key == 's_phone':
            p = re.compile('[A-Za-z]')
            if p.search(value):
                raise forms.ValidationError("Phone number cannot contain "
                                            "letters")

            try:
                number = phonenumbers.parse(value, "US")

                if (not phonenumbers.is_valid_number(number) or not
                        phonenumbers.is_possible_number(number)):
                    raise forms.ValidationError("")

                value = phonenumbers.format_number(number,
                                                   phonenumbers.
                                                   PhoneNumberFormat.E164)
                cleaned_data['value'] = value[2:]
            except Exception as ex:
                raise forms.ValidationError("s_phone must be a phone number")

        elif key in validated_ei:
            uw_validate(value, key, validated_ei[key])

        return cleaned_data
github alephdata / aleph / services / extract-entities / entityextractor / result.py View on Github external
def _parse(self, number, region=None):
        try:
            num = phonenumbers.parse(number, region)
            if phonenumbers.is_possible_number(num):
                if phonenumbers.is_valid_number(num):
                    return num
        except phonenumbers.NumberParseException:
            pass
github Sotera / pst-extraction / spark / phone_numbers.py View on Github external
excerpt_start = match.start() - EXCERPT_CHAR_BUFFER
        if excerpt_start < 0:
            excerpt_start = 0
        excerpt_prefix = source_txt[ excerpt_start : match.start() ]

        phone_number_obj = None

        try:
            # print "phone guess: %s"%value_normalized
            # Try using the 'phonenumbers' module to parse the number. Note that we need to prefix
            # 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