Code to Validate Date using javascript

Lakhangarg
Posted by Lakhangarg under JavaScript category on | Views : 2361
This Code is Used to Validate a Date entered in a TextBox:

function ValidateDate()
{
//debugger;
var varDate=document.getElementById('txtDate');
var divMessage=document.getElementById('divMessage');
var Days=30;
if(varDate.value.length<1)
{
divMessage.innerHTML= "Please Enter a Date.";
varDate.style.borderColor="red";
return false;
}
else
{
var DateSplit= varDate.value.split('/');
try
{
if(DateSplit[1] == 1 || DateSplit[1] == 3 || DateSplit[1]==5 || DateSplit[1]==7 || DateSplit[1]==8 || DateSplit[1]==10 || DateSplit[1]==12)
Days=31;
else if (DateSplit[1]==2 & DateSplit[2]%4 !=0)
Days=28;
else if (DateSplit[1]==2 & DateSplit[2]%4 ==0)
Days=29;
else if (DateSplit[1] == 4 || DateSplit[1] == 6 || DateSplit[1]==9 || DateSplit[1]==11)
Days=30;

if(DateSplit[0]<Days || DateSplit[0]>1)
{
divMessage.innerHTML= "Enter a Valid Day.";
varDate.style.borderColor="red";
return false;
}
if(DateSplit[1]<12 || DateSplit[1]>1)
{
divMessage.innerHTML= "Enter a Valid Month.";
varDate.style.borderColor="red";
return false;
}
if(DateSplit[2].length<4 || DateSplit[2]<1800)
{
divMessage.innerHTML= "Enter a Valid Year.";
varDate.style.borderColor="red";
return false;
}
varDate.style.borderColor="";
divMessage.innerHTML= "Entered Date is Correct.";
}
catch(ex)
{
alert(ex);
}
}
}

Comments or Responses

Login to post response