Skip to main content

Contact Card Validator — Real-World Integration Project

You've learned four essential skills in this chapter: creating and manipulating strings, formatting output with f-strings, and safely converting between types. Now it's time to apply everything to solve a real problem—a Contact Card Validator that cleans, validates, and formats contact information.

Every application needs to collect user data: registration forms, profile pages, contact forms, CRM systems. Messy input like " JOHN DOE ", invalid emails, or non-numeric ages cause problems. Your job as a developer is to clean and validate this data before storing it.

This project is different from exercises. You'll start by describing what the program should do, then build it with AI as your partner, test it with realistic data, and validate that it works correctly. This is how real programming works: you solve a problem someone has, not just demonstrate concepts.

By the end of this lesson, you'll have built a practical tool that validates contact information using all Chapter 21 concepts—string methods, f-strings, type casting, and validation—skills you'll use in every application you build.


Phase 1: Program Design — Describing Intent First

Before writing code, the most important step is clarifying what problem you're solving. This is the intent-first approach that separates professional developers from code copiers.

What is the Contact Card Validator?

The Contact Card Validator is a practical tool that solves a real problem: cleaning and validating messy contact information.

The Problem: Users enter contact data inconsistently:

  • Names: " john doe ", "JANE SMITH", "bob_jones"
  • Emails: "user@example", "invalid.com", "@nouser"
  • Phone: "(555) 123-4567", "555.123.4567", "5551234567"
  • Age: "25", "twenty-five", "99999"

The Solution: A validator that:

  1. Cleans names (Lesson 2: String Methods):

    • Removes extra whitespace: strip()
    • Fixes capitalization: title() for proper names
    • Replaces underscores with spaces: replace("_", " ")
  2. Validates emails (Lesson 2: String Methods):

    • Checks for @ symbol: find("@")
    • Ensures not empty after cleaning: strip()
    • Basic format validation
  3. Formats phone numbers (Lesson 2: String Methods):

    • Removes formatting characters: replace("(", "").replace(")", "").replace("-", "").replace(".", "").replace(" ", "")
    • Validates length (10 digits)
    • Displays in standard format
  4. Validates age (Lesson 4: Type Casting):

    • Converts string to integer: int(age_str)
    • Validates reasonable range (0-120)
    • Handles invalid input gracefully
  5. Displays formatted contact card (Lesson 3: F-Strings):

    • Shows cleaned data in professional format
    • Indicates validation status for each field

💬 AI Colearning Prompt

"I'm building a contact validator. What fields should I validate? What are common data quality issues with names, emails, and phone numbers? How should I handle invalid data?"

This conversation helps you understand the problem domain before coding.

Design Intent — User Story

User Story: As a developer building a registration form, I need to clean and validate contact information so that my database contains high-quality data.

User Interaction Flow:

1. Program starts → Explains what it does
2. Asks for name → User enters messy name
3. Cleans name → Shows original vs. cleaned
4. Asks for email → User enters email
5. Validates email → Shows valid/invalid with reason
6. Asks for phone → User enters phone
7. Formats phone → Shows cleaned number
8. Asks for age → User enters age
9. Validates age → Converts and validates range
10. Displays contact card → Shows all cleaned data formatted nicely

🎓 Expert Insight

In real programming, you're solving problems for users. The Contact Card Validator solves data quality problems every application faces. You're not just learning string methods—you're learning when to use strip() (always for user input), title() (for names), and find() (for validation). This is professional development: understanding the problem before writing a single line of code.


Phase 2: Building Your Validator — AI-Guided Implementation

Now let's build the Contact Card Validator. This code demonstrates all Chapter 21 concepts solving a real problem.

Code Example 5.1: Basic Contact Card Validator

This is a working version that validates and formats contact information using all Lessons 1-4 concepts:

Loading Python environment...

What This Code Demonstrates:

  • Lesson 1 (String Fundamentals): Using len(), string indexing for phone formatting (cleaned_phone[0:3]), type validation with type()
  • Lesson 2 (String Methods): strip() for all input, title() for names, lower() for emails, multiple replace() calls for phone cleaning, find() for email validation, isdigit() for number validation
  • Lesson 3 (F-Strings): Formatting output throughout (f"Name: {cleaned_name}"), formatting phone number with slicing in f-string
  • Lesson 4 (Type Casting): Converting age string to integer with validation, checking valid ranges, boolean logic for adult check

Real-World Application:

This code solves actual problems:

  • Names: Handles " john doe ""John Doe", "bob_smith""Bob Smith"
  • Emails: Validates basic format, cleans whitespace, normalizes to lowercase
  • Phone: Accepts any format → converts to standard (555) 123-4567
  • Age: Validates numeric input and reasonable ranges

Specification Reference & Validation:

  • Spec: Contact validator must clean and validate contact data using Lessons 1-4 concepts
  • AI Prompt Used: (The above code implements the design intent from Phase 1)
  • Validation Steps:
    1. Run with messy name (" john DOE ") → Cleans to "John Doe"
    2. Run with valid email ("[email protected]") → Validates successfully
    3. Run with formatted phone ("(555) 123-4567") → Extracts digits and reformats
    4. Run with valid age ("25") → Converts and validates range
    5. Run with invalid data → Shows helpful error messages

Code Example 5.2: Enhanced Validator with Functions and Error Tracking

This version adds organization, better error handling, and validation summary:

Loading Python environment...

Why This Version Is Better:

  1. Organization: Functions handle one validation task each (single responsibility)
  2. Reusability: Each validator can be called independently or reused in other programs
  3. Comprehensive Feedback: Returns both cleaned data AND validation status with messages
  4. Type Hints: Uses advanced type hints (tuple[str, bool], int | None) showing professional patterns
  5. Validation Summary: Shows all results together, not step-by-step (better UX)
  6. All-or-Nothing: Contact card only displays if ALL fields valid (real-world requirement)

Real-World Pattern:

This is how professional applications validate forms:

  1. Collect all input first
  2. Validate each field independently
  3. Show all errors at once (not one-by-one)
  4. Only proceed if everything is valid

Note: Functions and tuples are from Chapter 25. This example shows how your validator could evolve; focus on understanding the validation patterns, not memorizing function syntax.


Phase 3: Testing Your Validator — Real-World Scenarios

Now you validate that your contact validator works correctly with realistic data. Testing means running your code with messy, invalid, and edge-case inputs—just like real users provide.

🤝 Practice Exercise

Ask your AI: "I've built a Contact Card Validator. Help me test it with these realistic scenarios:

  1. Name with extra whitespace and wrong capitalization
  2. Email missing @ symbol or domain
  3. Phone number in different formats (dashes, parentheses, dots)
  4. Age as text instead of number, or unrealistic ages (like 999)
  5. All fields empty

For each, what should my program output? What makes good validation? Then explain the clean → validate → convert → use pattern."

Expected Outcome: You understand how to validate real user input and predict edge cases your program should handle gracefully.

Test Cases You Should Try

Test 1: Messy Name

Enter full name:   john_doe
Expected: Cleans to "John Doe" (strips whitespace, replaces underscore, title case)
Validation: ✓ Valid name

Test 2: Valid Contact

Name: Sarah Wilson
Email: [email protected]
Phone: (555) 123-4567
Age: 28
Expected: All fields validate, contact card displays, adult status shown

Test 3: Invalid Email

Email: userexample.com (missing @)
Expected: Shows "✗ Email must contain @ (not at start/end)"
Email: @example.com (@ at start)
Expected: Shows same error (invalid format)

Test 4: Phone Number Variations

Phone: 555-123-4567     → Formatted as (555) 123-4567 ✓
Phone: (555) 123-4567 → Formatted as (555) 123-4567 ✓
Phone: 555.123.4567 → Formatted as (555) 123-4567 ✓
Phone: 5551234567 → Formatted as (555) 123-4567 ✓
Phone: 123-456 → ✗ Invalid (only 6 digits)
Phone: 555-123-456a → ✗ Invalid (contains letter)

Test 5: Age Validation

Age: 25        → ✓ Valid age, Adult
Age: 17 → ✓ Valid age, (not adult)
Age: 0 → ✓ Valid age (newborn)
Age: 150 → ✗ Invalid: Age must be between 0 and 120
Age: twenty → ✗ Invalid: Age must be a number
Age: -5 → ✗ Invalid: Age must be a number (negative fails isdigit())

Test 6: Edge Case - All Empty

Name: (press Enter)
Email: (press Enter)
Phone: (press Enter)
Age: (press Enter)
Expected: All fields fail validation, contact card not displayed, clear error messages

Test 7: Realistic Messy Data

Name:   BOB_SMITH   (extra spaces, underscores, all caps)
Email: [email protected] (uppercase)
Phone: 1-555-123-4567 (includes country code digit)
Age: 30 (whitespace)

Expected behavior:
- Name: Cleans to "Bob Smith" ✓
- Email: Cleans to "[email protected]" ✓
- Phone: ✗ Invalid (11 digits instead of 10)
- Age: Cleans to "30" ✓

Phase 4: Reflection — Connecting Back to Chapter 21

The most important part of this project is understanding how all Chapter 21 concepts solve a real problem together.

What Lessons 1-4 Did Your Validator Use?

String Fundamentals (Lesson 1)

Your validator uses:

  • String creation: All contact fields start as strings from user input
  • String length: len(cleaned_name) validates non-empty names, len(cleaned_phone) checks 10 digits
  • String indexing: cleaned_phone[0:3] extracts area code for formatting
  • Immutability understanding: Each cleaning operation returns a new string

String Methods (Lesson 2)

Your validator applies (most critical lesson!):

  • strip(): Applied to ALL user input first (professional best practice)
  • title(): Fixes name capitalization ("john doe""John Doe")
  • lower(): Normalizes emails ("[email protected]""[email protected]")
  • replace(): Cleans phone numbers (multiple calls to remove ()-. characters)
  • find(): Validates email format (checks for @ symbol)
  • isdigit(): Validates phone digits and age numbers

Key Insight: Every method solves a specific real-world problem. You now know WHEN to use each method, not just HOW.

F-String Formatting (Lesson 3)

Your validator uses:

  • Variable embedding: f"Name: {cleaned_name}" displays contact fields
  • Expressions: f"Phone must be 10 digits (got {len(digits)})" shows why validation failed
  • Conditional formatting: f"{'✓ Valid' if name_valid else '✗ Invalid'}" shows status
  • String slicing in f-strings: f"({cleaned_phone[0:3]}) {cleaned_phone[3:6]}-{cleaned_phone[6:10]}" formats phone

Type Casting (Lesson 4)

Your validator demonstrates:

  • String to integer: int(cleaned_age) converts age for range validation
  • Validation before conversion: cleaned_age.isdigit() prevents crashes
  • Boolean logic: age >= 18 determines adult status, all_valid = name_valid and email_valid and phone_valid and age_valid checks all fields
  • Error handling: When conversion fails, returns None and shows message (no crashes)

How These Skills Connect in Real Applications

Think of it like a professional workflow:

  1. Input arrives messy → User types " JOHN DOE ", "555-123-4567", " 25 "
  2. Clean immediatelystrip() removes whitespace (ALWAYS do this first)
  3. Transform formattitle() for names, lower() for emails, digit extraction for phones
  4. Validate structure → Check length, check for required characters (@), check numeric
  5. Convert types → String "25" becomes integer 25 for math/logic
  6. Format output → F-strings present clean, professional results
  7. Handle errors gracefully → No crashes; helpful messages explain what's wrong

Critical Pattern: Clean → Validate → Convert → Use

This exact pattern appears in:

  • Registration forms (exactly what you built!)
  • User profile updates
  • Payment processing (credit card numbers)
  • Address validation
  • Search queries
  • API request validation
  • Database input sanitization

Why This Matters

You didn't just learn string methods—you learned data quality engineering. Every application has the same problem:

Users provide messy, inconsistent, invalid data. Your job is to clean, validate, and standardize it before using it.

The Contact Card Validator demonstrates this principle. The skills you practiced here apply to every form, every database input, every API endpoint you'll ever build.


Next Steps: Extending Your Validator

Once your basic validator works, you can add real-world features:

Enhanced Validations:

  • Email domain validation: Check if domain has . (e.g., [email protected] has .com)
  • Phone area code validation: Validate specific area codes (e.g., (555) is not a real US area code)
  • Name length limits: Enforce minimum/maximum name lengths
  • International phone formats: Support formats from different countries

Additional Fields:

  • Address validation: City, state, ZIP code
  • Date of birth: Validate date format and calculate age automatically
  • Username validation: Check length, allowed characters, no spaces
  • Password strength: Check length, special characters, numbers

Data Storage (Chapter 27: File Handling):

  • Save contacts to file: Store validated contacts in CSV or JSON format
  • Load and edit: Read existing contacts and update them
  • Search contacts: Find contacts by name or email

User Experience (Chapter 22: Control Flow):

  • Retry on error: Let users re-enter invalid data instead of restarting
  • Menu system: Choose to add, view, edit, or delete contacts
  • Batch import: Validate multiple contacts at once from a file

Ask your AI companion how to add any of these features. Each one uses Chapter 21 concepts plus skills from upcoming chapters.


Try With AI: Contact Validator Capstone Challenge

You've completed all 4 lessons of Chapter 21. Now integrate everything—strings, methods, f-strings, and type casting—into a production-quality contact validator. This is YOUR capstone project with AI as your code review partner.

Try With AI

Ready to integrate strings, methods, f-strings, and type casting into a contact validator?

🔍 Explore Integration:

"Show me how strings, methods, f-strings, and type casting work together. Create a contact validator that: cleans names (strip, title), validates email (contains '@'), parses age from string to int, formats output with f-strings. Explain how each component contributes."

🎯 Practice Production Validation:

"Build a production-ready contact validator for: name=' john doe ', email='JOHN@EXAMPLE', age='25'. Use string methods to clean, f-strings to format output, type casting to convert age. Add validation: name not empty, email contains '@', age converts successfully. Show complete code with type hints."

🧪 Test Edge Cases:

"Test this validator with edge cases: (1) empty name, (2) email without '@', (3) age='twenty-five' (non-numeric), (4) age='3.14' (decimal). For each, show what breaks and how to handle it gracefully with try/except or validation checks."

🚀 Apply to Your Data Intake:

"I'm building a data intake form for [describe your application]. Help me create a comprehensive validator: clean text fields with string methods, validate formats, convert types with error handling, format output with f-strings. Make it impossible for bad input to crash the system."