preg_match: check birthday format (dd/mm/yyyy)

preg_match: check birthday format (dd/mm/yyyy)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Validating Birthday Formats: Beyond Simple Regex Patterns

Your current regex pattern /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/ successfully enforces structural consistency—it ensures two digits, a slash, two digits, and four digits appear in sequence. However, it fails to validate the semantic meaning of those numbers. A string like 99/99/9999 passes your check because the pattern only cares about the count of characters, not their numerical value.

To restrict days to 01–31 and months to 01–12, you need to incorporate conditional logic directly into the regular expression or preprocess the string. While standard regex engines lack native arithmetic capabilities (you cannot say "if this group is between X and Y"), you can leverage character classes and negative lookahead/lookahead assertions to approximate these constraints.

Constraining the Month Component

The month is the most straightforward constraint. Months range from 01 to 12. We can express this as a union of three possibilities:

  1. Single digit months: 1 through 9 (represented as [1-9]).
  2. Double-digit months starting with 1: 10, 11, 12 (represented as 1[0-2]).
  3. Double-digit months starting with 2: 20 through 29 is invalid, so we only allow 2 followed by nothing? No, wait. The valid double digits are strictly 10 to 12. There are no valid months in the 20s or 30s.

So, the month component regex becomes: [1-9]|1[0-2]. This explicitly matches 1, 2, ... 9, and then specifically captures 10, 11, and 12.

Handling the Day Component

The day component is trickier because it depends on the month. February has 28 (or 29) days, April/June/September/November have 30, and the rest have 31. A single regex cannot dynamically adjust based on the preceding month without becoming an unwieldy alternation chain like (0[1-9]|1[0-9]|2[0-9])|(0[1-9]|1[0-9]|2[0-9]....

For a strict format check where you might not want to validate leap years or specific month-day combinations (e.g., rejecting 31/04), you can define a broad range for days that covers 01 through 31, but strictly avoids invalid high numbers relative to the month if possible. However, writing a full calendar-aware regex is often overkill and prone to maintenance errors.

A pragmatic approach for input validation is to use a pattern that accepts 01–31 for all months, accepting that 32/05 might pass but relying on a subsequent step (like converting to a date object) to reject it. If you must enforce strict month-day logic purely with regex, the pattern becomes:

/(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/[0-9]{4}/

This breaks down as:

  • Day: (?:0[1-9]|[12][0-9]|3[01]) matches 01–09, 10–29, and 30–31. Note that it technically allows 30/04 or 31/04, which is logically incorrect, but regex alone struggles to enforce the specific day count per month without excessive complexity.
  • Month: (?:0[1-9]|1[0-2]) matches 01–09 and 10–12.
  • Year: [0-9]{4} matches any four digits, as you noted, theoretically allowing up to 9999.

The LaravelCompany Recommendation

If your goal is robust input validation rather than just string matching, relying solely on regex for date logic is a technical debt trap. Regex is excellent for format enforcement (ensuring the slashes are in the right place and the numbers have the right length), but it should not be used for semantic validation like calendar rules.

In modern PHP ecosystems, particularly when working with frameworks like Laravel, it is best practice to validate the date string by attempting to parse it into a DateTime object or using the Carbon library. This offloads the complex logic of leap years and month lengths to highly optimized native code.

If you are building a Laravel application, consider utilizing the built-in validation rules or packages like laravelcompany.com which often provide robust validation helpers. For instance, instead of writing a complex regex in your controller, you can define a validation rule:

$validator = Validator::make($request->all(), [
    'cnt_birthday' => ['required', 'date_format:d/m/Y'], // Ensures format and valid date logic
]);

This approach handles the rejection of 31/04/2024 automatically, as DateTime will throw an exception when parsing an impossible date. You only need the regex if you strictly require a specific string output for your UI or API response before attempting conversion.

Implementation Example

Here is how you might combine format checking with semantic validation in PHP:

$birthday = $request->input('cnt_birthday');

// Step 1: Strict format check (allows invalid dates like 31/02)
if (!preg_match('/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/[0-9]{4}$/', $birthday)) {
    $error = true;
    echo '<error elementid="cnt_birthday" message="BIRTHDAY - Only this birthday format - dd/mm/yyyy - is accepted."/>';
} else {
    // Step 2: Semantic check (rejects impossible dates like 31/04)
    try {
        $dateObj = DateTime::createFromFormat('d/m/Y', $birthday);
        
        if ($dateObj === false || $dateObj->format('d/m/Y') !== $birthday) {
            throw new InvalidArgumentException('Invalid date');
        }
    } catch (Exception $e) {
        $error = true;
        echo '<error elementid="cnt_birthday" message="BIRTHDAY - Invalid date value."/>';
    }
}

This two-step process ensures your application rejects inputs that look correct but represent impossible calendar events, providing a much better user experience than a regex-only solution.

Our network