CodexBloom - Programming Q&A Platform

Regex scenarios to Match Date Formats with Optional Leading Zeros in JavaScript

👀 Views: 432 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
regex javascript validation JavaScript

I'm having a hard time understanding I'm integrating two systems and I tried several approaches but none seem to work. I'm working on a personal project and I'm trying to validate date formats in JavaScript using regex, specifically to match dates in both 'YYYY-MM-DD' and 'YYYY-M-D' formats, where the month and day can optionally have leading zeros. However, my current regex is not capturing the dates correctly when they do not have leading zeros. Here's the regex I've been using: ```javascript const dateRegex = /^(\d{4})-(\d{2}|\d{1})-(\d{2}|\d{1})$/; ``` When I test this with the following dates: ```javascript const dates = ['2023-01-15', '2023-1-5', '2023-12-30', '2023-4-09']; ``` I get matches for '2023-01-15', '2023-12-30', and '2023-4-09', but it fails for '2023-1-5'. I expected it to match all of them including '2023-1-5'. Additionally, I tried modifying the regex to: ```javascript const dateRegex = /^(\d{4})-(0\d|[1-9])-(0\d|[1-9])$/; ``` But this also didn't yield the results I was looking for. I end up with an empty match for '2023-1-5'. To debug, I've used `console.log(dateRegex.test('2023-1-5'))`, which returns `false`. Is there a specific way I should construct my regex to allow for both leading zero and non-leading zero formats for months and days? Any help would be appreciated! Is there a better approach? For context: I'm using Javascript on macOS. Could someone point me to the right documentation?