JavaScript Validate Date


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.