Return to Snippet

Revision: 54990
at January 20, 2012 11:19 by pumpkinthehead


Initial Code
// Validates date inputs
function isDate(dateStr, testYear) {
	var dateObj;
	var	dateStamp;
	var	day;
	var	month;
	var year;
	var dateRegex;
	
	// Set regex pattern based to test for year or not.
	if(testYear === undefined || testYear == true) {
		testYear = true;
		dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/.exec(dateStr);
	} else {
		testYear = false;
		dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})$/.exec(dateStr);
	}
	
	// Validate string.
	if(dateRegex == null) {
		return false;
	}
	
	// Get day, month, and year if testYear selected (or by default).
	month = parseInt(dateRegex[0]) - 1; // Subtract 1 because JS dates are 0-11.
	day = parseInt(dateRegex[1]);
	if(testYear) {
		year = parseInt(dateRegex[2]);
	} else {
		year = 1999; // This is arbitrary so long as it isn't a leap year.
	}
	
	// Create dateObj.
	dateStamp = (new Date(year, month, day)).getTime();
	dateObj = new Date();
	dateObj.setTime(dateStamp);
	
	// Validate date.
	if (dateObj.getMonth() !== month ||	dateObj.getDate() !== day || dateObj.getYear() !== year) {
		return false;
	}
	
	return true;
}

Initial URL

                                

Initial Description
Find the date with or without a year and with double or single digit month or day.  Easily extendable to other date delimiters and formats.

Initial Title
Flexible JavaScript Date Validation w/ Regex

Initial Tags
regex, javascript, date, validation

Initial Language
JavaScript