1. 長度限制 <script type="text/javascript"> function test() { if(document.a.b.value.length>50) { alert("不能超過50個字符!"); document.a.b.focus(); return false; } } </script> <form name=a onsubmit="return test()"> <textarea name="b" cols="40" wrap="virtual" rows="6"></textarea> <input type="submit" name="Submit" value="check"/> </form> 2. 只能是漢字 <input onkeyup="value="/oblog/value.replace(/[^\u4E00-\u9FA5]/g,'')"/> 3. 只能是英文 function onlyEng() { if(!(event.keyCode>=65&&event.keyCode<=90)) event.returnvalue=false; } </script> <input onkeydown="onlyEng();"/> 4. 只能是數字 <script type="text/javascript"> function onlyNum() { if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105))) //考慮小鍵盤上的數字鍵 event.returnvalue=false; } </script> <input onkeydown="onlyNum();"/> 5. 只能是英文字符和數字 <input onkeyup="value="/oblog/value.replace(/[\W]/g,"'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"/> 6. 驗證郵箱格式 <script type="text/javascript"> function isEmail(strEmail) { if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true; else alert("oh"); } </script> <input type=text onblur=isEmail(this.value)/> 7. 屏蔽關鍵字(這裏屏蔽***和****) <script type="text/javascript"> function test() { if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ("****") == 0)){ alert(":)"); a.b.focus(); return false; } } </script> <form name=a onsubmit="return test()"> <input type=text name=b/> <input type="submit" name="Submit" value="check"/> </form> 8. 兩次輸入密碼是否相同 <from method=post action=""> <input type="password" id="input1"/> <input type="password" id="input2"/> <input type="button" value="test" onclick="check()"/> </from> <script type="text/javascript"> function check() { with(document.all){ if(input1.value!=input2.value) { alert("false") input1.value = ""; input2.value = ""; } else document.forms[0].submit(); } } </script> 路政管理系統應用: //非空驗證 function checkoname(){ var casename= document.all['caseInfo.casename'].value; if(casename==""){ alert("案由不能爲空!請輸入執法機構"); casename.focus(); return false; } return true; } //機構簡稱非空驗證 function checkcpunishbase(){ var cpunishbase=document.all['caseInfo.cpunishbase'].value; if(cpunishbase==""){ alert("處罰依據不能爲空!請輸入機構簡稱"); cpunishbase.focus(); return false; } return true; }