[thelist] [JS] isDate function

Joshua Olson joshua at waetech.com
Tue Mar 8 11:49:49 CST 2005


Hi list,

After searching the web for isDate functions I found myself unhappy with
most of them.  Too long, too tedious, etc.  So, I made my own to parse
normal US formatted dates (MM/DD/YYYY).  Can anybody spot a reason why the
following code wouldn't work?

function removeLeadingZeros(str)
{
  while (str.charAt(0) == '0')
    str = str.substr(1);
  return str;
}


function isDate(str)
{
  try
  { 
    arr = str.split('/');
    month = parseInt(removeLeadingZeros(arr[0])) - 1;
    day = parseInt(removeLeadingZeros(arr[1]));
    year = parseInt(removeLeadingZeros(arr[2]));
    var d = new Date(year, month, day);
    
    return d.getMonth() == month && d.getFullYear() == year && d.getDate()
== day;
  }
  catch(err)
  {
    return false;
  }
}

Basic premise... split the string at the brackets.. create a date object
based on the values, then compare the date object's components against the
original values.  If they match, everything was OK.  If not, fail.

<><><><><><><><><><>
Joshua Olson
Web Application Engineer
WAE Tech Inc.
http://www.waetech.com/service_areas/
706.210.0168 




More information about the thelist mailing list