如何验证yyyy-mm-dd与yyyymmdd格式的日期输入?自定义算法是否可行?
Hey there! Your core approach to handling date validation and conversion is totally sound—let’s break down why it works, plus some edge cases you’ll want to cover to make the solution bulletproof.
Why Your Initial Logic Is a Great Starting Point
Your three core rules align perfectly with the requirements:
- Reject inputs with letters: This is a quick, effective first check to filter out obvious garbage input.
- Normalize valid formats: Converting both
yyyy-mm-ddandyyyymmddto a consistentyyyy-mm-ddoutput makes downstream use of the date way easier. - Clear error messaging: The friendly error string keeps feedback straightforward for users.
Key Edge Cases to Add for Robustness
Your basic logic misses a few scenarios that could slip through as "valid" when they’re not. Here’s what to add:
Non-letter invalid characters
Inputs like2023/12/01,2023--12-01aren’t letters, but still invalid. Use a regex to enforce only the two allowed formats upfront:yyyy-mm-dd: Must be 10 characters, with-at positions 4 and 7, and all other characters digits.yyyymmdd: Must be 8 consecutive digits.
Invalid date values
A string like2023-02-30or20231301fits the format but isn’t a real date. You’ll need to validate that the year, month, and day actually correspond to a valid calendar date.
Example Implementation (JavaScript)
Here’s how to expand your logic to cover these cases:
function validateAndStandardizeDate(input) { // Step 1: Reject any input that doesn't match the two allowed formats const validFormatRegex = /^(\d{4}-\d{2}-\d{2}|\d{8})$/; if (!validFormatRegex.test(input)) { return "Sorry, wrong format bro!"; } // Step 2: Extract year, month, day from either format let year, month, day; if (input.includes('-')) { [year, month, day] = input.split('-'); } else { year = input.slice(0, 4); month = input.slice(4, 6); day = input.slice(6, 8); } // Step 3: Validate the date is a real calendar date // Use Date object to check validity (it auto-corrects invalid dates, so we compare values) const testDate = new Date(year, month - 1, day); if ( testDate.getFullYear() !== parseInt(year) || testDate.getMonth() + 1 !== parseInt(month) || testDate.getDate() !== parseInt(day) ) { return "Sorry, wrong format bro!"; } // Step 4: Return standardized format return `${year}-${month}-${day}`; }
How This Works
- The regex first ensures the input only matches your two allowed formats, filtering out any non-digit/non-hyphen junk (except the hyphens in the right places).
- We split or slice the input to get individual date components.
- The
Dateobject check catches invalid dates: if you pass2023-02-30, it’ll create a date for March 2nd, so comparing the original components to the Date’s values tells us it’s invalid.
Final Verdict
Your initial logic is absolutely feasible—you just need to add those extra validation steps to avoid edge-case bugs. With those tweaks, you’ll have a reliable date handler that meets all your requirements!
内容的提问来源于stack exchange,提问作者PostJavanese

