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

8
  • return (Date.parse(dateString) > 0); ? Commented Jun 6, 2013 at 11:18
  • 2
    I guess it's isNaN() not isNan(). Commented Jun 6, 2013 at 11:18
  • @TheNewIdiot right, but that was a typo and the problem in is in the parse part in my opinion Commented Jun 6, 2013 at 11:24
  • @Cobra_Fast but the number is already > 0 isn't it? Commented Jun 6, 2013 at 11:25
  • @Maarten yeah but if it fails, it will likely return false or null or some other value that would cause this test to fail. Commented Jun 6, 2013 at 11:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 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 Yes, if you can be 100% sure of the input format, then it will work.
Check this for validating the date : stackoverflow.com/questions/14693298/…
@ynos1234 why is that any better?
0

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

Very cool library.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.