项目中需要对用户在输入时进行一些年龄限制。于是做了一个sample,先测试了一下,功能已经实现。与大家分享。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div>
<input id="mydate" type="text" placeholder="mm/dd/yy"/>
<a id="btn" href="#">start counting</a>
</div>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script>
(function(){
var minAge=18, mydate,
EVENT_DATE_REGEXP = /^([0-9]{2})[-/.]([0-9]{2})[-/.][0-9]{4}$/,
EVENT_MONTH_REGEXP = /^(0[1-9]|1[012])[-/.]([0-9]{2})[-/.][0-9]{4}$/,
EVENT_DAY_REGEXP = /^([0-9]{2})[-/.](0[1-9]|[12][0-9]|3[01])[-/.][0-9]{4}$/,
PHONE_NUMBER_REGEXP = ['^(\\d{3})\\d{3}\\d{4}$','^(\\d{3}[ ])\\d{3}[ ]\\d{4}$','^(\\d{3}[-])\\d{3}[-]\\d{4}$','^(\\d{3}[.])\\d{3}[.]\\d{4}$','^([(]\\d{3}[)][ ])\\d{3}[-]?\\d{4}$'];
$('#btn').bind('click', grabData);
$("body").bind('nextEvt',shuchu);
function shuchu(){
var tempDate, value = nextEvt.mes;
if (!EVENT_DATE_REGEXP.test(value)) {
alert( 'You must enter a valid ' + 'testing Date' + ' in the format MM/DD/YYYY.');
} else {
if (!EVENT_MONTH_REGEXP.test(value)) {
alert( 'Please enter a valid month for the ' + 'testing Date' + '.');
}
if (!EVENT_DAY_REGEXP.test(value)) {
alert( 'Please enter a valid day for the ' + 'testing Date' + '.');
}
tempDate = value.replace(/[-|.]/g, '/');
var testingDate = (new Date().getTime() - new Date(tempDate).getTime()) / (1000 * 60 * 60 * 24 * 365);
console.log('new Date gettime' + new Date().getTime());
console.log('new Date tempDate' + new Date(tempDate).getTime());
console.log('plus equeals to:'+ (new Date().getTime()-new Date(tempDate).getTime()));
console.log('eqeals Year:'+ (new Date().getTime()-new Date(tempDate).getTime())/(1000 * 60 * 60 * 24 * 365));
console.log('testingDate:'+testingDate);
tempDate = Math.floor((new Date().getTime() - new Date(tempDate).getTime()) / (1000 * 60 * 60 * 24 * 365));
console.log('tempDate:'+tempDate);
if (minAge) {
if (minAge > tempDate) {
alert('You must be ' + minAge + ' years or older to enter.');
}
} else {
if (new Date().getTime() - new Date(value).getTime() < 0) {
alert('You must be born to enter!');
}
}
if (tempDate > 100) {
alert('You must be 100 years or younger to enter.');
}
}
}
var nextEvt = $.Event('nextEvt');
function grabData(){
mydate = $('#mydate').val();
if(mydate){
nextEvt.mes = mydate;
$("body").trigger('nextEvt');
}
}
})()
</script>
</body>
</html>
注意:其实这个方法里面我仅仅是在年龄上限制,其实就是对Year限制,所以并没有那么精确,当然具体这与需求有关,如果你们需要更加精确地限制同样可以在此基础上继续完善,其原理都是一样的。