Skip to content

Instantly share code, notes, and snippets.

@kirandasika
Last active August 29, 2015 14:17
Show Gist options
  • Save kirandasika/f1e43da5547e711934a8 to your computer and use it in GitHub Desktop.
Save kirandasika/f1e43da5547e711934a8 to your computer and use it in GitHub Desktop.
Validate a date string #JavaScript
// Validates whether the given date string is in MM/DD/YYYY format, and if it is a valid date.
var isValidDate = function (dateString) {
// Validate the date string for the format via regular expressions. In this case it is MM/DD/YYYY
var dateRegEx = new RegExp('^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d)$' ); // Date Format: MM/DD/YYYY
if (dateRegEx.test(dateString)) {
var dateTokens = dateString.split('/' );
var timestamp = Date.parse(dateString);
// Parsing the date in javascript into the no. of milliseconds since Jan 1, 1970 is
// an added line of defense to check whether the date format is correct.
if (!isNaN(timestamp)) {
// Date.parse() parses a date string even if it is logically incorrect.
// e.g. When you parse Feb 30, 2013, it gives you milliseconds till Mar 2, 2013 without any errors.
// Here comes the one-to-one checking of the actual month, day and year literals.
var date = new Date(dateString);
if (parseInt(date.getMonth(), 10) + 1 === parseInt(dateTokens[0], 10)
&& parseInt(date.getDate(), 10) === parseInt(dateTokens[1], 10)
&& parseInt(date.getYear(), 10) === parseInt(dateTokens[2], 10)) {
return true ;
}
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment