分类分类
2015-06-28 00:00作者:网管联盟
有时在做网站时,有时有的数据要用户输入时间,比如生日,在这里,我们说一下JS在客户端是如何验证用户输入的时间是否符合格式的!
这个JS验证程序如下,我们不必要细研究它的实现过程,保存起来,会使用就行了!
<script language=&javascript&>
//判断输入的日期是否正确
function CheckDate(INDate)
{ if (INDate==&&)
{return true;}
subYY=INDate.substr(0,4)
if(isNaN(subYY) || subYY<=0){
return true;
}
//转换月份
if(INDate.indexOf('-',0)!=-1){ separate=&-&}
else{
if(INDate.indexOf('/',0)!=-1){separate=&/&}
else {return true;}
}
area=INDate.indexOf(separate,0)
subMM=INDate.substr(area+1,INDate.indexOf(separate,area+1)-(area+1))
if(isNaN(subMM) || subMM<=0){
return true;
}
if(subMM.length<2){subMM=&0&+subMM}
//转换日
area=INDate.lastIndexOf(separate)
subDD=INDate.substr(area+1,INDate.length-area-1)
if(isNaN(subDD) || subDD<=0){
return true;
}
if(eval(subDD)<10){subDD=&0&+eval(subDD)}
NewDate=subYY+&-&+subMM+&-&+subDD
if(NewDate.length!=10){return true;}
if(NewDate.substr(4,1)!=&-&){return true;}
if(NewDate.substr(7,1)!=&-&){return true;}
var MM=NewDate.substr(5,2);
var DD=NewDate.substr(8,2);
if((subYY%4==0 && subYY%100!=0)||subYY%400==0){ //判断是否为闰年
if(parseInt(MM)==2){
if(DD>29){return true;}
}
}else{
if(parseInt(MM)==2){
if(DD>28){return true;}
}
}
var mm=new Array(1,3,5,7,8,10,12); //判断每月中的最大天数
for(i=0;i< mm.length;i++){
if (parseInt(MM) == mm[i]){
if(parseInt(DD)>31){return true;}
}else{
if(parseInt(DD)>30){return true;}
}
}
if(parseInt(MM)>12){return true;}
return false;}
</script>
使用方法如下:
if(CheckDate(myform.sDate.value)){
alert(&您输入的开始日期不正确(如:1980/07/17或1980-07-17)n 请注意闰年!&);myform.sDate.focus();return;
相关文章