日期输入的限制方法

项目中需要对用户在输入时进行一些年龄限制。于是做了一个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限制,所以并没有那么精确,当然具体这与需求有关,如果你们需要更加精确地限制同样可以在此基础上继续完善,其原理都是一样的。

转载于:https://www.cnblogs.com/santiago1983/archive/2012/02/29/2374619.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值