Skip to Content
Course content

114: Practice Exercise: Building an Email and Phone Number Validator

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're a bouncer at a high-end club. You aren't just checking if people have an ID; you're checking if that ID is legitimate. You're looking for specific markers: a government seal here, a birthdate in a certain format there, and a photo that actually looks like the person standing in front of you. If any of those pieces are missing or look "off," you don't let them in. You don't care if the person is nice; they either meet the criteria of a valid ID, or they don't.

In Python, when we validate an email or a phone number, we're acting as that bouncer. We aren't analyzing the meaning of the text; we're checking the structure. We use Regular Expressions (regex) as our rulebook to decide if a string of characters earns its "entry stamp" into our database.

Mapping the Rulebook to Regex

To build this validator, we need to translate those "bouncer rules" into patterns the re module understands. Here is how that mapping actually works in practice:

  • The "Start and End" markers: Just as a bouncer checks the whole ID from top to bottom, we use ^ and $. This ensures the entire string matches our pattern, not just a small piece of it hidden in the middle of a sentence.
  • The "Must-Have" characters: For an email, the @ and the . are non-negotiable. In regex, the dot is a special character (it usually means "any character"), so we have to escape it with a backslash \. to tell Python, "I literally mean a period."
  • The "Quantity" rules: A phone number can't have 50 digits. We use curly braces like {3} or {10} to specify exactly how many digits we expect in a specific block.

Building the Validation Logic

I've found that the cleanest way to handle this is by wrapping the logic in a class or a set of dedicated functions. This keeps your main program logic from getting cluttered with those dense, hard-to-read regex strings. I usually keep the patterns as constants at the top of the file so I can tweak them without hunting through the code.

import re

class ContactValidator:
    # Pattern: Start, alphanumeric/dots/plus, @, alphanumeric/dots, dot, 2-4 letters, end
    EMAIL_PATTERN = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    
    # Pattern: Supports (123) 456-7890, 123-456-7890, or 1234567890
    PHONE_PATTERN = r'^(\(\d{3}\)\s?|\d{3}-?)\d{3}-?\d{4}$'

    @classmethod
    def is_valid_email(cls, email):
        return bool(re.fullmatch(cls.EMAIL_PATTERN, email))

    @classmethod
    def is_valid_phone(cls, phone):
        return bool(re.fullmatch(cls.PHONE_PATTERN, phone))

# Quick test drive
test_email = "dev_mentor@python.org"
test_phone = "(555) 123-4567"

if ContactValidator.is_valid_email(test_email) and ContactValidator.is_valid_phone(test_phone):
    print("All clear! Both are valid.")
else:
    print("Something is wrong with the input.")

Where this usually goes wrong

One thing I want you to watch out for: regex is a rabbit hole. You can find "perfect" email regex patterns online that are three pages long to account for every single edge case in the global RFC standards. Trust me, you almost never need those. In the real world, we usually use a "good enough" pattern for basic structure and then send a verification email to actually prove the address exists. Don't let the quest for the "perfect" pattern stall your progress.




📋 Practical Task

The User Profile Sanitizer

You've been handed a list of user-submitted contact data, but it's a mess. Some users entered their phone numbers with parentheses, some with dashes, and some just typed random text. Your job is to build a "Sanitizer" script.

Requirements:

  • Create a list of dictionaries containing "dirty" data. Include at least 5 entries: some with valid emails/phones, some with invalid emails (e.g., missing the @), and some with invalid phones (e.g., too few digits).
  • Implement a script that iterates through this list and separates the users into two new lists: verified_users and flagged_users.
  • A user is only "verified" if both their email and phone number pass the validation patterns discussed in the lesson.
  • Print the final verified_users list to the console to show who made the cut.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.