31 March 2016

Validate a date - the simple way

 

 Introduction

How do you check if a date is valid? Let's see... Does the month selected has 30 or 31 days. But wait... there is the february it has only 28 days. And all 4 years there is a leap year. Except every 100 years. Pretty complex, isn't it?
But, there is a simple way!

How it works

Funny thing about Javascript is that you can create a date even with invalid values. It converts it into a valid date.
For example. If you want to create the date 32nd of March, it will make the 1st of April out if it. So all we have to do is to check if we get the date, we put in.

Requirements

None. Only JS itself.

Code

    function checkDate(year, month, day) {
        var d = new Date(year, month - 1, day);
        return d.getFullYear() == year && (d.getMonth() + 1) == month && d.getDate() == day;
    }

    checkDate(2016, 2, 28); // returns true
    checkDate(2016, 7, 35); // returns false

No comments:

Post a Comment