Python Tutorial: Phone Number Validation 📞

beginner
7 min

Python Tutorial: Phone Number Validation 📞

Welcome to our comprehensive guide on Python Phone Number Validation! In this tutorial, we will learn how to create a script that checks the validity of a phone number. This is a practical and useful skill, especially for web development projects. Let's get started!

Why Validate Phone Numbers? 💡

Validating phone numbers is essential for several reasons:

  1. It ensures the user enters a number in the correct format, reducing errors.
  2. It improves user experience by providing immediate feedback.
  3. It helps in maintaining data quality, as incorrect phone numbers can lead to communication issues.

Understanding Phone Number Formats 📝

Before we dive into the code, let's discuss common phone number formats:

  1. US format: (XXX) XXX-XXXX
  2. UK format: +XX XXXXXX
  3. International format: +XX XX XXXX

Where XX represents the country code, and XXXX represents the local number.

Writing the Phone Number Validation Script 🎯

Now, let's create a simple phone number validation script using Python.

python
def validate_phone_number(number): # Remove non-digit characters number = re.sub(r'\D', '', number) # Check if the number has the correct length if len(number) < 10 or len(number) > 15: return False # Check if the number follows a specific pattern if len(number) == 10 and number[0] == '1': # US format if len(number) == 11 and number[1:3] in ['2', '3', '4', '5', '6', '7', '8', '9']: # Area code if number[3:6] in ['2', '3', '4', '5', '6', '7', '8', '9']: # Local number if number[6:] in ['2', '3', '4', '5', '6', '7', '8', '9']: return True elif len(number) == 11 and number[0] == '0' and number[1] == '1': # UK format if number[2:] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: return True elif len(number) == 12 and number[0] == '0' and number[1] == '4' and number[2] == '4': # International format if number[3:] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: return True return False # Test the function number = '1234567890' if validate_phone_number(number): print('The phone number is valid.') else: print('The phone number is not valid.')

In the code above, we define a validate_phone_number function that checks the validity of a phone number. The function removes non-digit characters, checks the length, and verifies if the number follows a specific pattern for US, UK, and international formats.

Pro Tip: 💡

Don't forget to import the re module at the beginning of your script:

python
import re

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the first step in our phone number validation script?

Now that you've learned how to create a phone number validation script, you can apply this skill to various real-world projects. Happy coding! 🚀