JavaScript function to validate if the string is a valid date
function isValidDate(strDate)
{
// Consider the date format is entered as DD/MM/YYYY
// Regular Expression which validates the string with the above date format
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
// test if the string is a in valid format
if (dateFormat.test(strDate))
{
// Replace leading zeros to avoid the string concatenation
strDate = strDate.replace(/0*(\d*)/gi,"$1");
// Split the string to get DD MM YYYY values
var dateArray = strDate.split(/[\.|\/|-]/);
//Month value starts with zero so correct the month value
dateArray[1] = dateArray[1]-1;
// Correction in YYYY value
// If the date is of 2 digit and less that 50 then get the value and append it 2000 so that we can get actual year value and if the date is more than 50 then get the value and append it to 1900 to get exact year value.
if (dateArray[2].length < 4)
{
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 +
parseInt(dateArray[2]);
}
// Create a new date instance by using above date values and validate with actual values
var validDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (validDate.getDate() != dateArray[0] || validDate.getMonth() != dateArray[1] ||
validDate.getFullYear() != dateArray[2])
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
No comments:
Post a Comment