表单递交合法性检测-日期

 1<html>
 2<head>
 3<script language="JavaScript">   
 4<!--   
 5function testKey(e){   
 6chars= "0123456789/";   
 7e = window.event;   
 8if(chars.indexOf(String.fromCharCode(e.keyCode))==-1) window.event.keyCode=0;   
 9};   
10function valDate(M, D, Y){   
11Months= new Array(31,28,31,30,31,30,31,31,30,31,30,31);   
12Leap = false;   
13  
14if((Y % 4 == 0) && ((Y % 100 != 0) || (Y %400 == 0)))   
15Leap = true;   
16if((D < 1) || (D > 31) || (M < 1) || (M > 12) || (Y < 0))   
17return(false);   
18if((D > Months[M-1]) && !((M == 2) && (D > 28)))   
19return(false);   
20if(!(Leap) && (M == 2) && (D > 28))   
21return(false);   
22if((Leap) && (M == 2) && (D > 29))   
23return(false);   
24};   
25  
26function formatDate(dateForm){   
27cDate = dateForm.value;   
28dSize = cDate.length;   
29sCount= 0;   
30  
31if (document.Form1.Date.value == ""){   
32alert("请输入日期!");   
33return false ;   
34}   
35  
36if(cDate=='') return;   
37  
38for(var i=0; i < dSize; i++)   
39(cDate.substr(i,1) == "/") ? sCount++ : sCount;   
40if (sCount != 2){   
41alert("输入的日期格式必须是\n ''月/日/年''");   
42dateForm.select();   
43return(false);   
44};   
45//检测输入的年份是2位数还是4位数;   
46ySize = cDate.substring(cDate.lastIndexOf("/")+1,dSize).length   
47if(ySize<2 || ySize>4 || ySize == 3){   
48alert('您输入的日期错误 !');   
49dateForm.select();   
50return false;   
51};   
52//将输入的日期字符串分隔成3部分 (Month, Day & Year)   
53idxBarI = cDate.indexOf("/");   
54idxBarII= cDate.lastIndexOf("/");   
55strM = cDate.substring(0,idxBarI);   
56strD = cDate.substring(idxBarI+1,idxBarII);   
57strY = cDate.substring(idxBarII+1,dSize);   
58  
59strM = (strM.length < 2 ? '0'+strM : strM);   
60strD = (strD.length < 2 ? '0'+strD : strD);   
61if(strY.length == 2)   
62strY = (strY > 50 ? '19'+strY : '20'+strY);   
63dateForm.value = strM+'/'+strD+'/'+strY;   
64  
65ok = valDate(strM, strD, strY);   
66if(ok==false){   
67alert("您输入的日期错误 !");   
68dateForm.select();   
69return false;   
70};   
71};   
72  
73  
74\-->   
75</script>
76<title>日期合法性检测</title>
77</head>
78<body bgcolor="#FFFFFF" onload="javascript:document.Form1.Date.focus()">
79<form action="" method="post" name="Form1" onsubmit="return testKey(event)">   
80输入正确的日期(月/日/年):   
81<input maxlength="10" name="Date" onblur="formatDate(this)" size="10" type="text" value=""/>
82</form>
83</body>
84</html>

说明:此脚本的用途是比较全面地检测输入日期的合法性,除了做非空检测外,还有效地检测了不同年月日期的合法性问题。比如在不是闰年的2月输入了29日等。黄色代码与脚本的检测无关,作用是页面读出页面后光标停留在日期文本框内。可以不要。

注意:(1)

1<form>标签中表单的名字Form1和日期文本框的名字Data(加重字体)与脚本是有关的,也就是说你如果改动了它们的名字,凡是在脚本中引用From1和Data的部分都要修改。切切!!!   
2  
3(2)Javascript是大小写敏感的,所以注意大小写的区别和一致性原则。   
4  
5(3)此脚本应该与CGI/ASP等服务器端的递交处理程序配合使用,用于客户端的合法性检测。本例没有将submit按钮作上去,你所处理的表单中可能包括更多的内容。   
6  
7这里仅仅提供了一个脚本思路,你不一顶非要全部照搬脚本,可以仅仅取脚本的一部分使用(主要是算法)。</form>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus