Skip to content

Instantly share code, notes, and snippets.

@draeton
Created August 16, 2011 04:24
Show Gist options
  • Save draeton/1148431 to your computer and use it in GitHub Desktop.
Save draeton/1148431 to your computer and use it in GitHub Desktop.
Date validation method
/**
* takes an input element and validates its value as a date by converting
* to a date object and then back to a string. Defaults to month-day-year order
*
* @param {HTMLElement} dateField The HTML input element to validate
* @param {Boolean} [isDMY] Is the value in day-month-year order? Optional
* @return {Boolean} is valid
*/
function isValidDate(dateField, isDMY) {
var strDate = dateField.value,
dateRegex = /(\d{1,2})[\-\s\/\.](\d{1,2})[\-\s\/\.](\d{4})/,
dateArray,
day,
month,
year,
testDate;
// test strDate against dateRegex and return an array with matched values
dateArray = strDate.match(dateRegex);
if (!dateArray) {
// date doesn't match the regular expression so not valid
return false;
}
// dateArray now contains an array with the year, month and day.
if (!isDMY) { // US style
day = +dateArray[2]; // using '+' sign to convert from str to number
month = +dateArray[1];
year = +dateArray[3];
} else {
day = +dateArray[1];
month = +dateArray[2];
year = +dateArray[3];
}
// create a new date object
testDate = new Date(year, month - 1, day);
// see if the date object's year, month, and day match our strings
if (testDate.getFullYear() !== year) {
return false;
}
if (testDate.getMonth() + 1 !== month) {
return false;
}
if (testDate.getDate() !== day) {
return false;
}
// if we passed these tests, we have a valid date
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment