check valid date javascript code example
Example 1: javascript validate date
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testDate))) {
return false;
}
Example 2: how to validate from and to date using date.parse in javascript
var stringval = '01/03/2012';
var testdate;
try {
testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
} catch (e)
{
alert(stringval + ' is not valid. Format must be MM/DD/YYYY ' +
'and the date value must be valid for the calendar.';
}
Example 3: javascript validate date
function isDate(ExpiryDate) {
var objDate,
mSeconds,
day,
month,
year;
if (ExpiryDate.length !== 10) {
return false;
}
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
month = ExpiryDate.substring(0, 2) - 1;
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
if (year < 1000 || year > 3000) {
return false;
}
mSeconds = (new Date(year, month, day)).getTime();
objDate = new Date();
objDate.setTime(mSeconds);
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
return true;
}
function checkDate(){
var ExpiryDate = document.getElementById(' ExpiryDate').value;
if (isDate(ExpiryDate)) {
alert('OK');
}
else {
alert('Invalid date format!');
}
}