vietean
vietean

Reputation: 3033

Date is invalid in Chrome with ISO format - tested with: 2012-11-31

Who will answer my question?

How can I validate a date using Javascript cross browser?

I use a invalid date: 2011-11-31 like below:

var d = new Date("2012-11-31")

In FF:

d = NaN // Date is invalid

In Chrome:

d.getFullYear();//2012
d.getDate();//1
d.getMonth();//11

Upvotes: 1

Views: 1136

Answers (2)

Esailija
Esailija

Reputation: 140220

Tested in IE7-9, chrome, opera, safari, firefox. Test here: http://jsfiddle.net/MRwAq/

You could do it like this:

(function(){
                             //This should be good enough initial filter, let the native Date decide if the number are valid
    var validStringRE = /^([0-9]{4})-([0-1][0-9])-([0-3][0-9])$/;

    function pad( num ) {
    return num < 10 ? "0"+num : num;
    }

    Date.prototype.getISOFormat = function(){
    return this.getFullYear() + "-" +
    pad( ( this.getMonth() + 1 ) ) + "-" +
    pad( this.getDate() );
    };

    function isValidISODate( date ) {
    var matches, a;
        if( !validStringRE.test( date.toString() ) ) {
        return false; //Get rid of anything but "NNNN-NN-NN"
        }

    matches = date.match( validStringRE );

    a = new Date( +matches[1], +matches[2] - 1, +matches[3], 0, 0, 0, 0 );

        if( isNaN( a ) ) {
        return false; //firefox, ie
        }

        if( a.toString().toLowerCase() === "invalid date" ) {
        return false; //chrome in some cases, opera, safari
        }

    return a.getISOFormat() === date; //browsers that "conveniently" calculate
    }

window.isValidISODate = isValidISODate;
})()

Then:

var isValid = isValidISODate("2012-11-31");
//false

var isValid = isValidISODate("2012-11-30");
//true

Upvotes: 2

davin
davin

Reputation: 45525

You can't reliably do that. See section 15.9.4.2 of the standard:

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

Essentially, if you enter an invalid date, the language can do whatever it wants, i.e. give back NaN or try and "fix" it as it sees fit.

Esailija posted a pragmatic way to test that seems to work well.

Upvotes: 1

Related Questions