check if date is correct in javascript

index.tsx
function isDateValid(dateString) {
    // First, check if the input is a valid date format
    if (!/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
        return false;
    }

    // Second, check if the date is an actual valid date
    const dateObj = new Date(dateString);
    return !isNaN(dateObj.getTime());
}

// Example usage
console.log(isDateValid('2022-12-25')); // Output: true
console.log(isDateValid('2022-13-25')); // Output: false
441 chars
15 lines

related categories

gistlibby LogSnag