validate 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 verify timestamp format in javascript
var valid = (new Date(timestamp)).getTime() > 0;
var valid = (new Date('2012-08-09')).getTime() > 0;
var valid = (new Date('abc')).getTime() > 0;
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!');
}
}
Example 4: how to validate input type=date in javascript
function isValidDate(d){
return !isNaN((new Date(d)).getTime());
}