javascript check valid date (Pure javascript)

If you want to use pure javascript to check a date, here it is:

The idea is coming from this post.


Date.isValidDate= function(y,m,d){
if(typeof y != 'number') y = new Date().getFullYear();
if(typeof m != 'number') m = new Date().getMonth();
if(typeof d != 'number') d = new Date().getDate();

switch(m){
case 0: case 2: case 4: case 6: case 7: case 9: case 11:
return new Date(y, m, d).getDate() <= 31;
break;
case 3: case 5: case 8: case 10:
return new Date(y, m, d).getDate() <= 30;
break;
case 1:
return new Date(y, m, d).getDate() <= 29;
break;
default:
return false;
break;
}
}


Usage:
Date.isValidDate(2012, 1, 29) => True    //Feb 29, 2012
Date.isValidDate(2012, 0, 31) => True    //Jan 31, 2012
Date.isValidDate(2013, 1, 29) => False    //Feb 29, 2013
Date.isValidDate(2012, 3, 31) => False    //Apr 31, 2013

Remind:
m - Month in Javascript, ranging from 0(Jan) - 11(Dec)

Please comment here if you found any problem.

Comments

Popular posts from this blog

TCPDF How to show/display Chinese Character?

Wordpress Load balancing: 2 web servers 1 MySQL without any Cloud services

Using wget bypass htaccess username password 401 authorization