Maarten
Maarten

Reputation: 4671

Validate date in Javascript

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..?

Upvotes: 0

Views: 83

Answers (2)

Bas Slagter
Bas Slagter

Reputation: 9929

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.

Upvotes: 2

Mediator
Mediator

Reputation: 15378

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

Very cool library.

Upvotes: 0

Related Questions