JS Input Validation – II (Date)
It is very important to validate the data supplied by the user through a form before we process it. In this tutorial, we discuss how we can perform JavaScript date validation in “dd/mm/yyyy” or “dd-mm-yyyy” format.
In the following examples, a JavaScript function is used to check a valid date format against a regular expression. Later we take each part of the string supplied by user (i.e. dd, mm and yyyy) and check whether dd is a valid date, mm is a valid month or yyyy is a valid year. We have also checked the leap year factor for the month of February. We have used ‘/’ and ‘-‘ character as a separator within the date format but you are free to change that separator the way you want.
Explanation
The JS code mentioned below is better understood, if we have analyzed the following regular expression for date validation.
Regular Expression Pattern:
/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/
The complete code is given below.
HTML embedded JS code to validate a date:
<html>
<head>
<title>JavaScript date validation</title>
<script type="text/javascript">
function validateDate(text)
{
var pattern = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if(text.value.match(pattern))
{
document.frm.txt.focus();
var opera1 = text.value.split('/');
var opera2 = text.value.split('-');
lopera1 = opera1.length;
lopera2 = opera2.length;
if(lopera1>1) {
var pdate = text.value.split('/');
}
else if(lopera2>1) {
var pdate = text.value.split('-');
}
//Colecting day, month and year information
var dd = parseInt(pdate[0]);
var mm = parseInt(pdate[1]);
var yy = parseInt(pdate[2]);
if(mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12) {
//For the months of January, March, May, July, August, October and December
if(dd>31) {
alert('Invalid date format!');
return false;
}
}
else if(mm==4||mm==6||mm==9||mm==11) {
//For the months of April, June, September and November
if(dd>30) {
alert('Invalid date format!');
return false;
}
}
//For the month of February
else if(mm==2 && dd<=29) {
var s = false;
if(yy%400==0 || (yy%100!=0 && yy%4==0))
s = true;
if(s==false)
alert("Invalid date format!");
return s;
}
else if(mm==2 && dd>29) {
alert('Invalid date format!');
return false;
}
}
else
{
alert("Invalid date format!");
document.frm.txt.focus();
return false;
}
}
</script>
</head>
<body onload='document.frm.txt.focus()'>
<h2>Input a date and Submit</h2>
<form name="frm" action="test.html" onSubmit="return validateDate(document.frm.txt)">
<input types="text" name ="txt"/>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Note: We must implement the web page named “test.html” as mentioned in the previous code.