Forum
Validating date and time value on the client side before sending it to server for server's validation might spoil your visiotr and save your server's load. To do this, we can use JavaScript.
Here, we will provide you with two JavaScript user defined functions to validate date value and time value.
Source code
Here is the function to validate a date:
function is_valid_date(elm){
var allow_blank = true;
var min_year = 1902;
var max_year = (new Date()).getFullYear();
var error_msg = "";
// regular expression to match required date format
re = /^(d{1,2})/(d{1,2})/(d{4})$/;
if(elm.value != ""){
if(regs = elm.value.match(re)){
if(regs[1] < 1 || regs[1] > 31)
error_msg = "Invalid value for day: " + regs[1];
else if(regs[2] < 1 || regs[2] > 12)
error_msg = "Invalid value for month: " + regs[2];
else if(regs[3] < min_year || regs[3] > max_year)
error_msg = "Invalid value for year: " + regs[3] + " - must be between " + min_year + " and " + max_year;
}else
error_msg = "Invalid date format: " + elm.value;
else if(!allow_blank)
error_msg = "Empty date not allowed!";
if(error_msg != ""){
alert(error_msg);
elm.focus();
return false;
}
return true;
}
Here is the function to validate a time:
function is_valid_time(elm){
var error_msg = "";
// regular expression to match required time format
re = /^(d{1,2}):(d{2})(:00)?([ap]m)?$/;
if(elm.value != ''){
if(regs = elm.value.match(re)){
if(regs[4]){
// 12-hour time format with am/pm
if(regs[1] < 1 || regs[1] > 12)
error_msg = "Invalid value for hours: " + regs[1];
}else{
// 24-hour time format
if(regs[1] > 23)
error_msg = "Invalid value for hours: " + regs[1];
}
if(!error_msg && regs[2] > 59)
error_msg = "Invalid value for minutes: " + regs[2];
}else
error_msg = "Invalid time format: " + elm.value;
}
if(error_msg != ""){
alert(error_msg);
elm.focus();
return false;
}
return true;
}
Usage example:
function check_form(form) {
if(!is_valid_date(form.startdate)) return false;
if(!is_valid_time(form.starttime)) return false;
if(!is_valid_date(form.enddate)) return false;
return true;
}
Adjusting the code for different date formats
Visitors from some countries may find it confusing that we're using the dd/mm/yyyy date format instead of the American or other standards. Modifying the code to account for these differences is quite simple and involves only minor changes.
US Date Format MM/DD/YYYY
In the is_valid_date function above you only need to replace references to regs[1] with regs[2] and vice-versa to reflect the change in order of the day and month values.
European Format YYYY-MM-DD
In the is_valid_date function above you only need to change the regular expression (re) to /^(d{4})-(d{1,2})-(d{1,2})/ and then replace references to regs[1] with regs[3] and vice-versa as the year and day values have now changed position.