简体   繁体   中英

Javascript validation of date select boxes

I have created 3 select boxes containing days, months and year. What I really would like is to check after the 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.

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM