1

So my problem is this:

new Date('01/32/1980') //January 32, 1980 (invalid)

Running this javascript in Chrome results in 'Invalid Date'
Running this javascript in Firefox results in a date of February 01, 1980

I've seen so many questions where people have different problems with the javascript date parser between browsers, but not this specific case.

I need to validate dates in the javascript, but something like this doesn't work as expected between browsers:

if(isNaN(new Date('1/32/1980').getTime())){
    //I expect this to be a valid date
}else{
    //I expect this to be an invalid date
}

They way Chrome parses '1/32/1980', an invalid date, this code works and drops into the else block. Firefox, in this exact same scenario, shows valid and drops into the valid section.

Am I missing something, is there a better way to validate this string?

Gobo
  • 687
  • 1
  • 6
  • 16

1 Answers1

0

The potential answer response with the RegEx is very messy and still doesn't completely cover this.

I went with a more clean looking solution using JQuery:

$.datepicker.parseDate('mm/dd/yy','1/32/1980')

I just wrapped this up like so:

function isValidDate(strDate, strDateFormat){
    try{
        $.datepicker.parseDate(strFormat, strDate);
    } catch (e) {
        return false;
    }
    return true;
}

Jquery will throw an an "Invalid Date" exception in all browsers. This works exactly as I needed. Sure, this is meant to be used for a widget, but it's logic is pretty solidly community tested.

Gobo
  • 687
  • 1
  • 6
  • 16