Course contentsShow
← JavaScript
Lesson 1731 of 2,72336. Regular ExpressionsFree lesson

Common Pattern: Phone Numbers and Dates

Flexible patterns for matching various phone number and date formats with optional delimiters.

Common Pattern: Phone Numbers and Dates

You'll learn how to craft flexible regular expressions that handle the messy real-world variations in phone numbers and date formats.

Why This Is Tricky

Phone numbers and dates are deceptively complex. Users might type "(555) 123-4567", "555-123-4567", "555.123.4567", or even "5551234567". Dates come as "12/31/2024", "2024-12-31", "31-12-2024", and more. You need patterns that accept common variations without being so loose they match garbage.

Phone Number Patterns

The key is making delimiters optional and flexible:

// Basic US phone: optional area code, flexible separators
const phonePattern = /^\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$/;

phonePattern.test("(555) 123-4567");  // true
phonePattern.test("555-123-4567");    // true
phonePattern.test("555.123.4567");    // true
phonePattern.test("5551234567");      // true

The \(? and \)? make parentheses optional. [-.\s]? accepts a dash, dot, space, or nothing. Capture groups let you extract or reformat the parts.

Date Patterns

Dates require alternation for different orderings:

// MM/DD/YYYY or MM-DD-YYYY
const usDate = /^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})$/;

// YYYY-MM-DD (ISO-style)
const isoDate = /^(\d{4})-(\d{2})-(\d{2})$/;

usDate.test("12/31/2024");   // true
usDate.test("3-5-2024");     // true
isoDate.test("2024-12-31");  // true

Use [\/\-] to allow slash or dash. Remember: these patterns don't validate that "13/45/2024" is an invalid date—just that the format matches.

Key Takeaway: Match phone numbers and dates by making delimiters optional with ? and using character classes for separators; focus on format flexibility, not semantic validation.