JAVASCRIPT

Validate and Extract YYYY-MM-DD Dates with Regex

Use regular expressions in JavaScript to validate strings against the YYYY-MM-DD date format and extract the date components for parsing.

function isValidAndExtractDate(dateString) {
  const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
  const match = dateString.match(dateRegex);
  
  if (match) {
    const year = parseInt(match[1], 10);
    const month = parseInt(match[2], 10);
    const day = parseInt(match[3], 10);
    
    // Basic date sanity check (e.g., month 1-12, day 1-31)
    if (month >= 1 && month <= 12 && day >= 1 && day <= 31) {
      // Further validation can be added here (e.g., check for valid days in specific months)
      return {
        isValid: true,
        year: year,
        month: month,
        day: day
      };
    }
  }
  return { isValid: false, year: null, month: null, day: null };
}

// Usage:
// console.log(isValidAndExtractDate("2023-10-26"));
// // Output: { isValid: true, year: 2023, month: 10, day: 26 }
// console.log(isValidAndExtractDate("2023-13-01")); // Invalid month
// // Output: { isValid: false, year: null, month: null, day: null }
// console.log(isValidAndExtractDate("26-10-2023")); // Incorrect format
// // Output: { isValid: false, year: null, month: null, day: null }
How it works: The `isValidAndExtractDate` JavaScript function validates whether a string matches the `YYYY-MM-DD` date format and, if so, extracts its year, month, and day components. It uses a regular expression with capturing groups to parse the string. Beyond simple format matching, it includes basic numerical checks for month and day ranges to prevent obviously invalid dates, returning an object indicating validity and the parsed components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs