The intention of below prog is to validate the input date using java script.
User has to enter the date in 'MM/DD/YYYY' format in the text box . On loosing the focus from the text field , the input date should be validated
Following Program will validate the user entered data using java script
Document : Hi.html
Date Validation in Java script
Author : murali
--%>
<html>
<script>
function check_date()
{
var check = 0;
var orderDate= document.dateForm.orderDate.value;
if(orderDate.length==0)
{
//do nothing when nothing entrered
return true;
}
if(orderDate.length!=10)
{
//user should enter in mm/dd/yyyy of length 10 , if not
alert('Invalid Date len'+orderDate.length);
document.dateForm.orderDate.focus();
return false;
}
var datePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!datePattern.test(orderDate))
{
alert('Invalid Date. Plz enter date in mm/dd/yyyy format');
document.dateForm.orderDate.focus();
return false;
}
var dateSplit = orderDate.split("/");
var day = dateSplit[1] ;
var month =dateSplit[0];
var year =dateSplit[2];
if(month>12 || day>31)
{
alert('day / month error');
return false;
}
var leap = 0;
if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
{
leap = 1;
}
if ((month == 02) && (leap == 1) && (day > 29))
{
check=1;
}
if ((month == 02) && (leap != 1) && (day > 28))
{
check=1;
}
if((day > 30) && ((month == 04) || (month == 06) || (month == 09) || (month ==11)))
{
check=1;
}
if(check==1)
{
alert('Invalid Date');
document.dateForm.orderDate.focus();
return false;
}
alert('Valid date');
return true;
}
</script>
<body>
<form name="dateForm" >
Enter Date in (MM/DD/YYYY) Format <input type="text" name="orderDate" onblur="check_date()"/>
</form>
</body>
</html>
SAMPLE OUTPUT
No comments:
Post a Comment