Friday, July 22, 2011

Javascript Date validation

I wanted to validate the date.. So i searched for a script and found this one . It wz really useful.

// check date JavaScript function
// if date is valid then function returns true, otherwise returns false
function isDate(txtDate){
var objDate;  // date object initialized from the txtDate string
var mSeconds; // milliseconds from txtDate
// date length should be 10 characters – no more, no less
if (txtDate.length != 10) return false;
// extract day, month and year from the txtDate string
// expected format is mm/dd/yyyy
// subtraction will cast variables to integer implicitly
var day   = txtDate.substring(3,5)  – 0;
var month = txtDate.substring(0,2)  – 1; // because months in JS start with 0
var year  = txtDate.substring(6,10) – 0;
// third and sixth character should be /
if (txtDate.substring(2,3) != ‘/’) return false;
if (txtDate.substring(5,6) != ‘/’) return false;
// test year range
if (year < 999 || year > 3000) return false;
// convert txtDate to the milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
// compare input parameter date and created Date() object
// if difference exists then date isn’t valid
if (objDate.getFullYear() != year)  return false;
if (objDate.getMonth()    != month) return false;
if (objDate.getDate()     != day)   return false;
// otherwise return true
return true;

// how to use isDate() JavaScript function
// this function is called on button click event
function checkDate(){
// define date string to test
var txtDate = document.getElementById(‘txtDate’).value;
// check date and print message
if (isDate(txtDate)) alert(‘OK’);
else alert(‘Invalid date format!’);

No comments:

Post a Comment

Constructor Chaining