This function validates a string date in digit formats delimited by a character, e.g. dd/mm/yyyy, mm/dd/yyyy
/*
Param :
1)the date in string data type
2)[optional - string - default is "/"] the date delimiter, most likely "/" or "-"
3)[optional - int - default is 0] the position of the day component when the date string is broken up via the String.split function (into arrays)
4)[optional - int - default is 1] the position of the month component when the date string is broken up via the String.split function (into arrays)
5)[optional - int - default is 2] the position of the year component when the date string is broken up via the String.split function (into arrays)
Return : a javascript date is returned if the params are OK else null
*/
function IsValidDate(strDate, strDelimiter, iDayPosInArray, iMonthPosInArray, iYearPosInArray) {
var strDateArr; //a string array to hold constituents day, month, and year components
var dtDate; //our internal converted date
var iDay, iMonth, iYear;
//sanity check
//no integer checks are performed on day, month, and year tokens as parsing them below will result in NaN if they're invalid
if (null == strDate || typeof strDate != "string")
return null;
//defaults
strDelimiter = strDelimiter || "/";
iDayPosInArray = undefined == iDayPosInArray ? 0 : iDayPosInArray;
iMonthPosInArray = undefined == iMonthPosInArray ? 1 : iMonthPosInArray;
iYearPosInArray = undefined == iYearPosInArray ? 2 : iYearPosInArray;
strDateArr = strDate.split(strDelimiter);
iDay = parseInt(strDateArr[iDayPosInArray],10);
iMonth = parseInt(strDateArr[iMonthPosInArray],10) - 1; // Note: months are 0-based
iYear = parseInt(strDateArr[iYearPosInArray],10);
dtDate = new Date(
iYear,
iMonth, // Note: months are 0-based
iDay);
return (!isNaN(dtDate) && dtDate.getFullYear() == iYear && dtDate.getMonth() == iMonth && dtDate.getDate() == iDay) ? dtDate : null; // Note: months are 0-based
}
Example call:
var strDate="18-01-1971";
if (null == IsValidDate(strDate)) {
alert("invalid date");
}