Flexible JavaScript Date Validation w/ Regex


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

Find the date with or without a year and with double or single digit month or day. Easily extendable to other date delimiters and formats.


Copy this code and paste it in your HTML
  1. // Validates date inputs
  2. function isDate(dateStr, testYear) {
  3. var dateObj;
  4. var dateStamp;
  5. var day;
  6. var month;
  7. var year;
  8. var dateRegex;
  9.  
  10. // Set regex pattern based to test for year or not.
  11. if(testYear === undefined || testYear == true) {
  12. testYear = true;
  13. dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/.exec(dateStr);
  14. } else {
  15. testYear = false;
  16. dateRegex = /^([0-9]{1,2})\/([0-9]{1,2})$/.exec(dateStr);
  17. }
  18.  
  19. // Validate string.
  20. if(dateRegex == null) {
  21. return false;
  22. }
  23.  
  24. // Get day, month, and year if testYear selected (or by default).
  25. month = parseInt(dateRegex[0]) - 1; // Subtract 1 because JS dates are 0-11.
  26. day = parseInt(dateRegex[1]);
  27. if(testYear) {
  28. year = parseInt(dateRegex[2]);
  29. } else {
  30. year = 1999; // This is arbitrary so long as it isn't a leap year.
  31. }
  32.  
  33. // Create dateObj.
  34. dateStamp = (new Date(year, month, day)).getTime();
  35. dateObj = new Date();
  36. dateObj.setTime(dateStamp);
  37.  
  38. // Validate date.
  39. if (dateObj.getMonth() !== month || dateObj.getDate() !== day || dateObj.getYear() !== year) {
  40. return false;
  41. }
  42.  
  43. return true;
  44. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.