Posted By

ckester on 08/15/08


Tagged

javascript date validate


Versions (?)

JavaScript Validate Date


 / Published in: JavaScript
 

URL: http://omnicode.blogspot.com/2008/05/checkvalidate-date-string-in-javascript.html

NOT MY CODE. I was looking for a good code that would validate the date in JavaScript and I found this function. I thought it was worth keeping so I decided to post it on here as opposed to clutter my bookmarks with one more link. Once again I take no credit for this code, I found it here: http://omnicode.blogspot.com/2008/05/checkvalidate-date-string-in-javascript.html . All credit goes to Sonny

  1. // Checks if a given date string is in
  2. // one of the valid formats:
  3. // a) M/D/YYYY format
  4. // b) M-D-YYYY format
  5. // c) M.D.YYYY format
  6. // d) M_D_YYYY format
  7. function isDate(s)
  8. {
  9. // make sure it is in the expected format
  10. if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
  11. return false;
  12.  
  13. // remove other separators that are not valid with the Date class
  14. s = s.replace(/[\-|\.|_]/g, "/");
  15.  
  16. // convert it into a date instance
  17. var dt = new Date(Date.parse(s));
  18.  
  19. // check the components of the date
  20. // since Date instance automatically rolls over each component
  21. var arrDateParts = s.split("/");
  22. return (
  23. dt.getMonth() == arrDateParts[0]-1 &&
  24. dt.getDate() == arrDateParts[1] &&
  25. dt.getFullYear() == arrDateParts[2]
  26. );
  27. }
  28.  
  29. // test function to test the isDate function
  30. function test_isDate()
  31. {
  32. var arrDates = [
  33. '05/15/2008', '05-15-2008',
  34. '05.15.2008', '05_15_2008',
  35. '15/15/2008', '05/35/2008',
  36. '05/15/1908', '15-15-2008',
  37. 'a/1b/2008', '05/30/a008' ];
  38.  
  39. for (var d in arrDates)
  40. document.writeln("isDate('" + arrDates[d] + "') : " + isDate(arrDates[d]) + "<BR>");
  41. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: blackf0rk on July 11, 2009

I tested this, and when I insert a date such as 7/25/20093 it returns true. I suppose that this is technically a correct date, but not when it comes to saving it in any database.

You need to login to post a comment.