Regex Pattern for Date Formats
Date strings come in many formats and regex can catch obvious formatting errors before passing values to a date parser. This example covers ISO 8601 (YYYY-MM-DD), US format (MM/DD/YYYY), and European format (DD-MM-YYYY). Note that regex cannot validate calendar logic like leap years or month-end days — use a date library for semantic validation after the format check.
Example
/^d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01])$/
# ISO 8601 test cases:
2024-01-15
2024-12-31
2024-13-01
2024-00-15
not-a-date
2024-1-5
20240115FAQ
- Can regex validate dates like February 30?
- No. Regex checks format and ranges for each component independently but cannot verify that a date is a real calendar day. Use a date library like date-fns or Temporal for semantic validation.
- How do I match multiple date formats with one regex?
- Combine patterns with alternation using the | operator, wrapping each format in a non-capturing group (?:...) so the alternation applies to the entire format.
- What is the ISO 8601 date format?
- ISO 8601 uses YYYY-MM-DD ordering, which is unambiguous regardless of locale. It is the recommended format for APIs, databases, and file names.
Related Examples
Regex Pattern for Email Validation
Email validation regex is one of the most commonly written and miswritten patter...
Regex Pattern for IP AddressesIP address validation is trickier than it looks because each octet must be betwe...
Regex Pattern for Hex ColorsHex color codes appear in CSS, design tokens, and configuration files. This exam...