JAVASCRIPT
Validate Date Format (YYYY-MM-DD)
Learn to validate dates in the YYYY-MM-DD format using a precise regular expression in JavaScript, perfect for form input validation.
function isValidDateFormatYYYYMMDD(dateString) {
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
return dateRegex.test(dateString);
}
// Examples:
// console.log(isValidDateFormatYYYYMMDD("2023-10-26")); // true
// console.log(isValidDateFormatYYYYMMDD("10-26-2023")); // false
// console.log(isValidDateFormatYYYYMMDD("2023-1-1")); // false (not two digits for month/day)
// console.log(isValidDateFormatYYYYMMDD("2023/10/26")); // false (wrong separator)
How it works: This JavaScript function checks if a string adheres to the YYYY-MM-DD date format. The regex `^\d{4}-\d{2}-\d{2}$` ensures the string starts with exactly four digits (`\d{4}`), followed by a hyphen, then exactly two digits (`\d{2}`), another hyphen, and finally two more digits, covering the year, month, and day respectively. The `^` and `$` anchors ensure the entire string must match the pattern. Note that this regex only validates the *format*, not the semantic correctness (e.g., it won't prevent "2023-13-40").