开发者

Javascript validation of date select boxes

开发者 https://www.devze.com 2022-12-13 03:49 出处:网络
I have created 3 select boxes containing days, months and year. What I really would like is to check after the 开发者_JAVA技巧user has selected a date, if the date is over a year from the current date

I have created 3 select boxes containing days, months and year. What I really would like is to check after the 开发者_JAVA技巧user has selected a date, if the date is over a year from the current date a message is displayed or so.

Im a little stumped on what to do. Any gidance would be great.

Thanks


var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');

var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];

// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();

// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();

The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.

The m-1 is because months in the Date constructor are an enum, which means January is 0.


Don't reinvent the wheel one more time. Use a library that does validation.


There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.

var userDate = new Date("11/29/2010");
var now      = new Date();
var year_ms  = 31556926000;

if ( userDate.getTime() - now.getTime() >= year_ms ) {
    // A year away
} else {
    // less than a year away
}
0

精彩评论

暂无评论...
验证码 换一张
取 消