Thursday, January 8, 2009

Javascript: Function To Validate Date Format DD/MM/YYYY

Please use the following java script to validate the Date in the format(DD/MM/YYYY) wherever you needed in transcription screens:

Place this code in the head section of your HTML/JSP and pass the value(12/12/2008) to function named as validateDateDDMMYYY(‘12/12/2008’)


function validateDateDDMMYYY(DateOfBirth)
{

var Char1 = DateOfBirth.charAt(2);
var Char2 = DateOfBirth.charAt(5);
// alert(Char1); alert(Char2);

var flag =false;

if ( Char1 =='/' && Char2 == '/' )
{
// alert ('valid positions of non numeric characters.');
flag = true;
}
else
{
// alert('invalid position of non numeric symbols');
flag =false;
}

var day;
var month;
var year;

day = DateOfBirth.substring(0,2);
month = DateOfBirth.substring(3,5);
year = DateOfBirth.substring(6,10);

// alert(day); alert(month);alert(year);
if( validDay(day) && validMonth(month) && validYear(year) && (flag ==true) )
{
// alert(' Valid Date')
return true;
}
else
{
alert('Invalid Date Format: Please enter DD/MM/YYYY for Date of Birth!');
return false;
}

} // end func

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}

return IsNumber;
} // end func


function validDay(day)
{
if ( IsNumeric(day) )
{
if( day >0 && day <32)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}

}// end func


function validMonth(month)
{
if ( IsNumeric(month) )
{
if( month >0 && month <13)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}// end func



function validYear(year)
{
var d = new Date();
var currentYear = d.getFullYear();

if( year.length!= 4) { return false; }

if ( IsNumeric(year) )
{
if( year >0 && year <=currentYear)
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}// end func

No comments: