如何用JavaScript正则表达式验证'MMMM DD YYYY'格式的日期?
Hey there! Let's tackle this date validation problem for the MMMM DD YYYY format (like January-01-2018). You already have experience validating other date formats with regex, so let's build on that—though we'll need an extra step beyond just regex to make sure the date is actually valid, not just formatted correctly.
Step 1: Regex for Format Validation
First, we need a regex that matches the full month names, two-digit day, four-digit year, all separated by hyphens. Here's what that looks like:
const formatRegex = /^(January|February|March|April|May|June|July|August|September|October|November|December)-(0[1-9]|[12]\d|3[01])-\d{4}$/;
Breakdown of the regex:
^(January|...|December): Matches exactly one of the 12 full month names at the start of the string.-(0[1-9]|[12]\d|3[01])-: Ensures the day is a two-digit number between 01 and 31, wrapped in hyphens.\d{4}$: Matches a four-digit year at the end of the string.
Step 2: Validate Actual Date Validity
Regex can only check the format, not whether the date is real (like February-30-2023 is formatted correctly but doesn't exist). We'll use JavaScript's Date object to verify the date is valid.
Putting it all together into a reusable function:
function validateMMMMDDYYYY(dateStr) { // First check if the format is correct const formatRegex = /^(January|February|March|April|May|June|July|August|September|October|November|December)-(0[1-9]|[12]\d|3[01])-\d{4}$/; if (!formatRegex.test(dateStr)) { return false; } // Split the date string into components const [monthName, day, year] = dateStr.split('-'); // Convert month name to its index (0-11, since Date uses 0-based months) const monthIndex = new Date(`${monthName} 1, ${year}`).getMonth(); // Create a Date object with the components const date = new Date(year, monthIndex, day); // Verify the date components match exactly (avoids auto-correction of invalid dates) return ( date.getFullYear() === parseInt(year) && date.getMonth() === monthIndex && date.getDate() === parseInt(day) ); }
Testing the Function
Let's test some cases to make sure it works:
console.log(validateMMMMDDYYYY("January-01-2018")); // ✅ true console.log(validateMMMMDDYYYY("February-29-2020")); // ✅ true (leap year) console.log(validateMMMMDDYYYY("February-29-2019")); // ❌ false (not a leap year) console.log(validateMMMMDDYYYY("April-31-2023")); // ❌ false (April only has 30 days) console.log(validateMMMMDDYYYY("Jan-01-2018")); // ❌ false (month isn't full name) console.log(validateMMMMDDYYYY("January-1-2018")); // ❌ false (day isn't two digits)
Why This Works
- The regex ensures the input string follows the exact
MMMM-DD-YYYYstructure. - The
Dateobject check catches invalid dates that regex can't—like February 30th or April 31st—by verifying that the created date doesn't get auto-corrected (JavaScript will adjust invalid dates to valid ones, e.g.,April-31-2023becomesMay-01-2023, so we compare the components to make sure they match the original input).
内容的提问来源于stack exchange,提问作者Dan

