Regex for Date (YYYY-MM-DD) — Pattern Explained with Examples
This regex validates dates in the ISO-inspired YYYY-MM-DD format. It checks that the year is four digits, the month is between 01 and 12, and the day is between 01 and 31. This pattern is useful for form validation, data import sanitization, and API input processing where date format consistency is required.
The Pattern
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/Pattern Breakdown
| Part | Meaning |
|---|---|
^ | Start of string |
\d{4} | Exactly four digits (year) |
- | Literal hyphen separator |
(0[1-9]|1[0-2]) | Month: 01-09 or 10-12 |
- | Literal hyphen separator |
(0[1-9]|[12]\d|3[01]) | Day: 01-09, 10-29, or 30-31 |
$ | End of string |
Matches
2024-01-151999-12-312023-06-012000-02-282024-07-04
Does NOT Match
2024/01/15— uses slashes instead of hyphens2024-13-01— month 13 is invalid2024-01-32— day 32 is invalid24-01-15— year is only 2 digits2024-1-1— missing leading zeros2024-00-01— month 00 is invalidFeb 15 2024— non-numeric format2024-01-— incomplete date
Language Examples
JavaScript
const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
console.log(dateRegex.test('2024-01-15')); // true
console.log(dateRegex.test('2024-13-01')); // false
console.log(dateRegex.test('2024-01-32')); // false
// Extract parts with capture groups
const match = '2024-01-15'.match(dateRegex);
if (match) {
console.log(`Year: ${match[0]}, Month: ${match[1]}, Day: ${match[2]}`);
}Python
import re
date_regex = r'^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$'
print(bool(re.match(date_regex, '2024-01-15'))) # True
print(bool(re.match(date_regex, '2024-13-01'))) # False
print(bool(re.match(date_regex, '2024-01-32'))) # False
# Extract parts
match = re.match(date_regex, '2024-01-15')
if match:
year, month, day = match.group(0), match.group(1), match.group(2)
print(f'{year}-{month}-{day}')Common Pitfalls
February 29 passes — The regex accepts
2024-02-29(valid leap year) but also2023-02-29(invalid — 2023 is not a leap year). Date validation requires a separate calendar check.Leap years not handled — The regex does not distinguish between common and leap years. Use a date library like
date-fnsor Python’sdatetimefor full validation.Separator flexibility — This pattern only accepts hyphens. Users may input slashes, dots, or spaces. Consider accepting multiple separators if needed.
Leading zeros required —
2024-1-1fails because single-digit months/days are not allowed. Decide whether leading zeros are mandatory for your use case.
Real-World Use Cases
- Form validation: Accepting user birth dates or event dates in a standardized format
- API input sanitization: Ensuring date parameters conform to ISO 8601 calendar date format
- Data import processing: Validating date columns in CSV or spreadsheet uploads
FAQ
Related Patterns
- Regex for Date (MM/DD/YYYY)
- Regex for ISO 8601 Date/Time
- Regex for Time (HH:MM)
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro