Validate entered From Date and To Date in web application text box field using JavaScript.
Validations:
- Date entered or not
- Entered date as valid or not (checking special characters)
- Entered date as valid date format or not
- Check To Date should be greater than From Date
The below JavaScript functions validate the above validation points with entered From and To Date in Web application screen.
This JavaScript function is called in Submit
onclientclick
event and passes From and To date text box field client id.
function isValidDate(varFrom, varTo) {
var fromdate, todate, dt1, dt2, mon1, mon2, yr1, yr2, date1, date2;
var chkFrom = document.getElementById(varFrom);
var chkTo = document.getElementById(varTo);
if (trim(document.getElementById(varFrom).value, '') == '') {
alert('From date should not be empty');
document.getElementById(varFrom).value = '';
document.getElementById(varFrom).focus();
return false;
}
else if (trim(document.getElementById(varTo).value, '') == '') {
alert('To date should not be empty');
document.getElementById(varTo).value = '';
document.getElementById(varTo).focus();
return false;
}
if (varFrom != null && trim(document.getElementById(varFrom).value, '') != '' && varTo != null && trim(document.getElementById(varTo).value, '') != '') {
if (checkdate(chkFrom) != true) {
document.getElementById(varFrom).value = '';
document.getElementById(varFrom).focus();
return false;
}
else if (checkdate(chkTo) != true) {
document.getElementById(varTo).value = '';
document.getElementById(varTo).focus();
return false;
}
else {
fromdate = trim(document.getElementById(varFrom).value, '');
todate = trim(document.getElementById(varTo).value, '');
dt1 = parseInt(fromdate.substring(0, 2), 10);
mon1 = parseInt(fromdate.substring(3, 5), 10);
yr1 = parseInt(fromdate.substring(6, 10), 10);
dt2 = parseInt(todate.substring(0, 2), 10);
mon2 = parseInt(todate.substring(3, 5), 10);
yr2 = parseInt(todate.substring(6, 10), 10);
date1 = new Date(yr1, mon1, dt1);
date2 = new Date(yr2, mon2, dt2);
if (date2 <= date1) {
alert("To date Should be greater than From date");
document.getElementById(varTo).value = '';
document.getElementById(varTo).focus();
return false;
}
}
}
return true;
}
function checkdate(input) {
var validformat = /^\d{2}\/\d{2}\/\d{4}$/
var returnval = false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else {
var monthfield = input.value.split("/")[1]
var dayfield = input.value.split("/")[0]
var yearfield = input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield - 1, dayfield)
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval = true
}
return returnval
}