JAVASCRIPT

Validate YYYY-MM-DD Date Format

Validate the YYYY-MM-DD date format using a regular expression in JavaScript to ensure consistent and correct date input from users.

const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

function isValidDate(dateString) {
  return dateRegex.test(dateString);
}

console.log(isValidDate("2023-10-26")); // true
console.log(isValidDate("2023-13-01")); // false (invalid month)
console.log(isValidDate("2023-10-32")); // false (invalid day)
How it works: This JavaScript regex specifically validates dates in the YYYY-MM-DD format. It checks for four digits for the year, a two-digit month (01-12), and a two-digit day (01-31). This regex ensures the structural correctness of the date format but does not validate leap years or the exact number of days in each specific month.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs