JAVASCRIPT
Validating YYYY-MM-DD Date Format
Ensure user input strictly adheres to the standard YYYY-MM-DD date format with a precise regular expression in JavaScript, preventing incorrect or malformed date entries in forms.
function isValidDate(dateString) {
const regex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
return regex.test(dateString);
}
console.log(isValidDate("2023-10-26")); // true
console.log(isValidDate("2023-02-29")); // true (valid leap year date, but regex doesn't check for actual leap year logic for Feb 29)
console.log(isValidDate("2023-13-01")); // false (invalid month)
console.log(isValidDate("2023-10-32")); // false (invalid day)
console.log(isValidDate("2023/10/26")); // false (wrong separator)
How it works: This snippet validates if a string matches the `YYYY-MM-DD` date format. The regex `^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$` ensures four digits for the year, a month between `01-12`, and a day between `01-31`. The `^` and `$` anchors ensure the entire string must match the pattern. Note that this regex does not perform full calendrical validation (e.g., checking if February 30th is valid).