Last active
August 26, 2019 21:45
-
-
Save wcarss/4646b661dee13eda1ec91ecb4a4e4506 to your computer and use it in GitHub Desktop.
javascript to check if a string is a valid YYYY-MM-DD-style date or datetime. This is more permissive than ISO 8601 but less permissive than the Date() constructor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* returns true/false on "is this string a valid date/datetime string" | |
* | |
* any credit for coolness goes to https://stackoverflow.com/a/44198641, | |
* and any blame for wrongness goes to me. :) | |
* | |
*/ | |
const isValidDate = dateString => { | |
let date = new Date(dateString); // we're gonna use both :0 | |
return ( | |
date && // make sure it's non-falsey, | |
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(dateString) && // roughly YYYY-MM-DD.* to stop e.g. new Date('0'), | |
Object.prototype.toString.call(date) === '[object Date]' && // is actually a date object, | |
!isNaN(date) // and is actually a *valid* date object. | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
e.g.