Check isValidDate in JavaScript

I’m currently using a JavaScript function to check if a given string represents a valid date. However, I’ve encountered a problem where certain non-date strings, like “SA-0001” or simple numbers inside strings like “1”, are erroneously being identified as valid dates.

function isValidDate(val) {
    if (typeof val === 'number') {
        return false;
    }
    const str = new Date(val);
    if (str != 'Invalid Date') {
        return true;
    } else {
        return false;
    }
}

In the incoming string, the format for valid date string varies and is not fixed, such as ‘yyyy-mm-dd’, and I aim to avoid restricting the backend to a specific format. How can I accurately determine if a given value represents a valid date without imposing a fixed format constraint?

Ex.

  • Input: ‘1999-01-01’ Expected result: true
  • Input: ’01-01-1999′ Expected result: true
  • Input: ’01-1999-01′ Expected result: true
  • Input: ‘Fri Mar 15 2024 18:19:30’ Expected result: true
  • Input: ’01-01′ Expected result: false
  • Input: ’01’ Expected result: false
  • Input: ‘sa-0001’ Expected result: false