Date Validation in JavaScript

Date Validation in JavaScript.
Date Time Validation in JavaScript.

Couple of days ago I had the need to validate an input as a Date in JavaScript.  I though for some time on the best way to do it so it would be as generic and stable as possible.

After finalizing my method, I decided to add it to our jsValidation.js file as well as uploading the method to my post to help others in need...

The method returns true if the date is a valid date and false if it's not.
    function isValidDate(d) {
        if (Object.prototype.toString.call(d) !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    }

The way to use this method will be:
    function Demo() {
        var d1 = new Date("invalid");
        var d2 = new Date("1985");
 
        var result_false = isValidDate(d1);
        var result_true = isValidDate(d2);
    }

Have fun with it,
Elad Shalom,
CTO at ITweetLive.com

Comments

Post a Comment

Popular posts from this blog

Cloud Computing Advantages and Disadvantages

Linked Files in Visual Studio 2010

BDD, TDD, and Everything Between