How to sanitize phone numbers before sending mass alerts

January 06, 2023
Written by

How to sanitize phone numbers before sending mass alerts

If you're planning on sending mass text notifications you'll want to make sure that the numbers you're sending to are valid. This post will quickly show how to use the Twilio Lookup API to sanitize your data, checking that:

  • Phone numbers are real
  • Phone numbers are formatted correctly
  • Phone numbers are mobile

Validating and sanitizing phone numbers will mean fewer API errors for sending to non-existent, incorrectly formatted, or landline numbers, giving you greater confidence in your system.

The Lookup API does not support bulk requests. If you anticipate a high volume of requests, please contact our sales team for more information and pricing.

Option #1: Normalize phone numbers with national formatting to E.164 and check their validity

This option requires that you know the ISO country code for every phone number, but assuming you have that information you can standardize national formats with parentheses or hyphens to an E.164 formatted number. E.164 is required for many Twilio API phone number inputs.

Copy the following code to a new file, I called mine sanitize.py:

from twilio.rest import Client


# Your Account Sid and Auth Token from twilio.com/console
# DANGER! Don't commit these tokens to Git. See http://twil.io/secure
account_sid = 'ACxxx'
auth_token = 'your_auth_token'

client = Client(account_sid, auth_token)

def format_number(pn, country_code="US"):
    result = client.lookups.v2.phone_numbers(
        pn).fetch(country_code=country_code)
    if (result.valid):
        return result.phone_number
    else:
        print("Error: invalid phone number {} for country code '{}'".format(
            pn, country_code))
        return None


print(format_number("(510) 867-5310"))
# +15108675310

Valid phone numbers will return the E.164 formatted number. If the function is called with an invalid phone number, it will return None and print an error message:

print(format_number("(510) 867-5310", country_code="GB"))
# None

print(format_number("(123) 555-1234"))
# None

Option #2: You have phone numbers in E.164 and want to check their validity

This code sample shows you how to run a phone number through the validation function of the API. Add this to the bottom of your Python file:

def is_valid_number(pn):
    result = client.lookups.v2.phone_numbers(pn).fetch()
    if not result.valid:
        print("Invalid number '{}': {}".format(
            pn, ', '.join(result.validation_errors)))
    return result.valid

print(is_valid_number("+4402077651182"))

For a valid phone number like the one in the example above, this will return True. Try it with an invalid phone number like +12345, the function will return False and provide the reasons.

print(is_valid_number("+4402077651182"))
# True
print(is_valid_number("+12345"))
# Invalid number '+12345': TOO_SHORT
# False

Check for mobile phone number type

If you want to check the phone number line type, use the following code. Contact Twilio Sales for pricing if you anticipate a large number of requests.

This code will check the line type of the phone number to see if it is mobile. The possible line types include mobile, landline, or nonFixedVoip among others.

def is_mobile(pn):
    result = client.lookups.v2 \
        .phone_numbers(pn) \
        .fetch(fields='line_type_intelligence')

    return result.line_type_intelligence['type'] == "mobile"

print(is_mobile("+15108675310"))
# True

Next steps after sanitizing phone numbers

The Twilio Lookup API is a great way to validate new inputs or sanitize data you already have. Once you have trust in the data check out more ways to engage with your customers:

I can't wait to see what you build.