Friday 9 September 2011

Best Date Validation using Javascript


function chkdate(inpdate)
{
idate=inpdate.value;
if(idate.length!=0)
{
if (idate.length > 10)
{
alert("date cannot exceed more than 10 characters and should be in format dd/mm/yyyy") ;
inpdate.focus();
inpdate.value=" ";
return false;
}
var dsh1 = idate.substring(3,2);
//alert (dsh1);
var dsh2 = idate.substring(6,5);
//alert (dsh2);
if (dsh1 != "/" )
{
alert ("Enter date in dd/mm/yyyy format >>> there is no '/' after day ");
inpdate.focus();
inpdate.value="";
return false
}
if (dsh2 != "/" )
{
alert ("Enter date in dd/mm/yyyy format >>> there is no '/' after month ");
inpdate.focus();
inpdate.value="";
return false;
}
var yr=idate.substring(6,10);
var mm=idate.substring(3,5);
var dd=idate.substring(0,2);
//alert(yr+' Year');
//alert(mm+' Month');
//alert(dd+' Day');
if (isNaN(dd))
{
alert ("Day of month should be numeric ");
inpdate.focus();
inpdate.value="";

return false;
}
if (isNaN(mm))
{
alert ("Month should be numeric ");
inpdate.focus();
inpdate.value="";

return false;
}
if (isNaN(yr))
{
alert ("Year should be numeric ");
inpdate.focus();
inpdate.value="";

return false;
}
if (yr < 1900)
{
alert ("Year should be greater than 1900 ");
inpdate.focus();
inpdate.value="";
return false;
}
//if(yr>2010)
//{
//alert("Year should be less than 2011");
//inpdate.focus();
//inpdate.value="";
//return false;
//}
if (yr.length != 4 )
{
alert ("Year should be 4 digits in year");
inpdate.focus();
inpdate.value="";
return false;
}
if (dd < 1)
{
alert ("Day of month cannot be less than 1 ");
inpdate.focus();
inpdate.value="";
return false;
}
if (dd > 31 )
{
alert ("Day cannot be Greater than 31 ");
inpdate.focus();
inpdate.value="";
return false;
}

if (mm > 12 || mm < 1 ) {
alert ("Month should be between 1 and 12 ");
inpdate.focus();
inpdate.value="";

return false;
}
if (mm == 6 || mm == 9 || mm==11 ) {
if (dd > 30 ) {
alert ("There are 30 days in June, September and November !! please correct day ");
inpdate.focus();
inpdate.value="";

return false;
}
}
if (mm==2)
{

var b=parseInt(yr /4);
if (isNaN(b)) {
alert( "Check no.of days in February NOT valid");
inpdate.focus();
inpdate.value="";

return false ;
}
if (dd>29) {
alert("Check no.of days in February NOT valid days in February cannot exceed 29");
inpdate.focus();
inpdate.value="";

return false ;
}
if (dd==29 && ((yr/4)!=parseInt(yr/4))) {
alert( "Check no.of days !! This is NOt leap year ");
inpdate.focus();
inpdate.value="";
return false ;
}
}
}
return true ;
}

How to call : onblur="chkdate(txtDoexp);"

No comments:

Post a Comment