Regex Not Capturing Date Formats with Optional Time in JavaScript - implementing Ambiguities
I've searched everywhere and can't find a clear answer. I'm trying to create a regex pattern in JavaScript that captures dates in the format `YYYY-MM-DD` and also handles an optional time component in the format `HH:MM`. However, I keep running into issues where my regex doesn't match certain valid date-time strings, particularly when the time part is omitted. Here's my current regex pattern: ```javascript const dateTimePattern = /^(\d{4})-(\d{2})-(\d{2})(\s+(\d{2}):(\d{2}))?$/; ``` When I test it with the following strings: ```javascript console.log(dateTimePattern.test('2023-10-05')); // should return true console.log(dateTimePattern.test('2023-10-05 14:30')); // should return true console.log(dateTimePattern.test('2023-13-01')); // should return false console.log(dateTimePattern.test('2023-10-05 25:00')); // should return false ``` I found that the pattern correctly matches the first two strings, but I'm having trouble validating the month and hour ranges. When I tested it with incorrect values, such as `2023-13-01`, it still returns true, which shouldn't happen. Is there a way to make the month and hour checks stricter without complicating the pattern too much? Any suggestions on how I can improve this regex to capture the desired formats and validate the ranges correctly? I'm currently using JavaScript ES6 and testing in the browser console. This is part of a larger service I'm building.