Validate if a string is a Date


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

Returns true if the string 'value' is a valid date.


Copy this code and paste it in your HTML
  1. //Value parameter - required. All other parameters are optional.
  2. function isDate(value, sepVal, dayIdx, monthIdx, yearIdx) {
  3. try {
  4. value = value.replace(/-/g, "/").replace(/\./g, "/");
  5. var SplitValue = value.split(sepVal || "/");
  6. if (SplitValue.length != 3) {
  7. }
  8.  
  9. //Auto detection of indexes
  10. if (dayIdx === undefined || monthIdx === undefined || yearIdx === undefined) {
  11. if (SplitValue[0] > 31) {
  12. yearIdx = 0;
  13. monthIdx = 1;
  14. dayIdx = 2;
  15. } else {
  16. yearIdx = 2;
  17. monthIdx = 1;
  18. dayIdx = 0;
  19. }
  20. }
  21.  
  22. //Change the below values to determine which format of date you wish to check. It is set to dd/mm/yyyy by default.
  23. var DayIndex = dayIdx !== undefined ? dayIdx : 0;
  24. var MonthIndex = monthIdx !== undefined ? monthIdx : 1;
  25. var YearIndex = yearIdx !== undefined ? yearIdx : 2;
  26.  
  27. var OK = true;
  28. if (!(SplitValue[DayIndex].length == 1 || SplitValue[DayIndex].length == 2)) {
  29. OK = false;
  30. }
  31. if (OK && !(SplitValue[MonthIndex].length == 1 || SplitValue[MonthIndex].length == 2)) {
  32. OK = false;
  33. }
  34. if (OK && SplitValue[YearIndex].length != 4) {
  35. OK = false;
  36. }
  37. if (OK) {
  38. var Day = parseInt(SplitValue[DayIndex], 10);
  39. var Month = parseInt(SplitValue[MonthIndex], 10);
  40. var Year = parseInt(SplitValue[YearIndex], 10);
  41. var MonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  42.  
  43. if (OK = (Month <= 12 && Month > 0)) {
  44.  
  45. var LeapYear = (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0));
  46. MonthDays[1] = (LeapYear ? 29 : 28);
  47.  
  48. OK = Day > 0 && Day <= MonthDays[Month - 1];
  49. }
  50. }
  51. return OK;
  52. }
  53. catch (e) {
  54. }
  55. }

URL: http://www.codeproject.com/Tips/144113/JavaScript-Date-Validation

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.