Quantcast
Viewing latest article 42
Browse Latest Browse All 58

Answer by Vijay Jagdale for Detecting an "invalid date" Date instance in JavaScript

Why am I writing a 48th answer after so many have tried before me?

For checking if it is Date Object and then a valid date object - dead simple:

return x instanceof Date && !!x.getDate();

Now for parsing date Text: Most of the solutions use Date.parse(), or "new Date()", both of which have issues. JavaScript parses a wide variety of formats and also is dependent on localization. For example, strings like "1" and "blah-123" will parse as a valid date.

Then there are responses that use a ton of code, or a mile-long RegEx, or use moment or some other frameworks - all of which is not ideal IMHO for something this simple.

If you have browsed all the way to the bottom of the pile, hopefully some of you will like this dead simple method to validate a date string. The trick is to use a simple Regex to to eliminate undesired formats, and then if that passes, use the Date.parse(). A failed parse results in NaN, which is "falsy". The "!!" converts that to a boolean "false".

function isDate(txt) { //this regx matches dates from 01/01/2000 - 12/31/2099       return /^\d?\d\/\d?\d\/20\d\d$/.test(txt) && !!Date.parse(txt);    }
TEST THE FUNCTION<br /><br /><input id="dt" value = "12/21/2020"><input type="button" value="validate" id="btnAction" onclick="document.getElementById('rslt').innerText = isDate(document.getElementById('dt').value)"> <br /><br />Result: <span id="rslt"></span>

Viewing latest article 42
Browse Latest Browse All 58

Trending Articles