Skip to content

Commit

Permalink
Add utility method to format phone numbers (move-coop#928)
Browse files Browse the repository at this point in the history
* added a utility method to format phone numbers

* updated to return none when number is invalid

* clarified docstring and cleaned

---------

Co-authored-by: mattkrausse <[email protected]>
  • Loading branch information
mkrausse-ggtx and mattkrausse authored Dec 19, 2023
1 parent caf6614 commit e631500
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
34 changes: 34 additions & 0 deletions parsons/utilities/format_phone_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import re


def format_phone_number(phone_number, country_code="1"):
"""
Formats a phone number in E.164 format, which is the international standard for phone numbers.
Example: Converts "555-555-5555" -> "+15555555555"
`Args:`
phone_number (str):
The phone number to be formatted.
country_code (str):
The country code to be used as a prefix.
Defaults to "1" (United States).
`Returns:`
str:
The formatted phone number in E.164 format.
"""
# Remove non-numeric characters and leading zeros
digits = re.sub(r"[^\d]", "", phone_number.lstrip("0"))

# Check if the phone number is valid
if len(digits) < 10:
return None

# Handle country code prefix
if not digits.startswith(country_code):
digits = country_code + digits

# Format the phone number in E.164 format
formatted_number = "+" + digits

return formatted_number
34 changes: 34 additions & 0 deletions test/test_utilities/test_format_phone_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import unittest
from parsons.utilities.format_phone_number import format_phone_number


class TestFormatPhoneNumber(unittest.TestCase):
def test_format_phone_number_local_us_number(self):
phone_number = "555-123-4567"
expected_result = "+15551234567"
self.assertEqual(
format_phone_number(
phone_number,
),
expected_result,
)

def test_format_phone_number_us_number_with_leading_1(self):
phone_number = "15551234567"
expected_result = "+15551234567"
self.assertEqual(format_phone_number(phone_number), expected_result)

def test_format_phone_number_international_number(self):
phone_number = "+441234567890"
expected_result = "+441234567890"
self.assertEqual(
format_phone_number(phone_number, country_code="44"), expected_result
)

def test_format_phone_number_invalid_length(self):
phone_number = "12345"
self.assertIsNone(format_phone_number(phone_number))


if __name__ == "__main__":
unittest.main()

0 comments on commit e631500

Please sign in to comment.