0

Note that this seems like a question that is asked many times, but somehow I can't get the most common solution to work. Most answers revolve around a solution like this one:

function isValidDate(){
  var dateString = '2001/24/33';
  return !isNaN(Date.parse(dateString));
}

In Firefox this returns a false as the result of that Date.parse is a number; 1041462000000.

How do I fix this..?

Maarten
  • 4,643
  • 7
  • 37
  • 51

2 Answers2

2

A good way to do this is to create new date object based on the string and compare the result of that object with the input string. If it is not the same, the date was invalid and JS did a fallback to a closer (valid) date. Something like this:

function isValidDate(str){
   var split = str.split('/');
   var date = new Date(split[0], split[1]-1, split[2]);

   return (date.getFullYear() == split[0] && date.getMonth()+1 == split[1] && date.getDate() == split[2]);
}

call with:

var isValid = isValidDate('2001/24/33');

Note: in this case the input string is assumed to be in a specific format. If your sure that it's always the same format there is not problem. If not, your need the work some more on this code.

As a sidenote: Use moment.js if you need to do extensive date operations.

Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
  • 2
    The problem with this is that the `Date` class accepts a few different formats for creation. So this will not work all the time. – Cobra_Fast Jun 06 '13 at 11:19
  • @Cobra_Fast as I can format the date however I like, in my case transforming it from 'dd-mm-yyyy' to 'yyyy/mm/dd' before handling it, would Baszz' solution work in all browser? – Maarten Jun 06 '13 at 12:01
  • @Maarten Yes, if you can be 100% sure of the input format, then it will work. – Cobra_Fast Jun 06 '13 at 12:02
  • Check this for validating the date : http://stackoverflow.com/questions/14693298/js-check-for-valid-date-format/28777878#28777878 – Sony Mathew Mar 06 '15 at 07:14
  • @ynos1234 why is that any better? – Bas Slagter Mar 09 '15 at 09:04
0

I suggest to use http://www.datejs.com/.

Very cool library.

Mediator
  • 14,951
  • 35
  • 113
  • 191