本文實例講述了JS實現的簡單表單驗證功能。分享給大家供大家參考,具體如下:
源代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><script type="text/javascript" src="myjs1.js"></script><link rel="stylesheet" type="text/css" href="myfile-2.css" rel="external nofollow" /></head><body><form name="f1">姓名:<input type="text" name="xm" /><br/>年齡:<input type="text" name="nl" />愛好:<input type= "checkbox" name="ah" />爬山<input type= "checkbox" name="ah" />游泳<input type= "checkbox" name="ah" />網球<input type= "checkbox" name="ah" />乒乓球<br/>密碼:<input type="password" name="mm"/><br/>重復密碼:<input type="password" name="cfmm"/><br/>備注:<textarea name="bz" rows="10" cols="20"></textarea><br/><input type="button" value="提交" onclick="checkit();"/></form></body></html>
myjs1.js文件代碼:
// JavaScript Documentfunction checkit(){ var flag = false; for(var i=0;i<document.forms[0].ah.length;i++){if(document.forms[0].ah[i].checked)//checked 表示被選中{flag = true;break;}}if(!flag)//沒有一個愛好被選中{alert("請至少選擇一個愛好!");return;//假如沒有找到,又返回去,直到找到!}if(document.forms[0].mm.value.length<9){alert("密碼長度必須在8位數以上!");document.forms[0].mm.focus();//讓密碼框獲取焦點,焦點是 可以根據應用配合完成一些自動化操作,比如登錄時輸入了錯誤的用戶名和密碼,回轉登錄頁后,可以讓用戶名輸入框自動獲得焦點,避免用戶重新定位。return;}if(document.forms[0].mm.value!=document.forms[0].cfmm.value){alert("兩次密碼輸入不一致,請重新輸入密碼!");return;}if(document.forms[0].bz.value==""){alert("請輸入備注!");}}
注意:在js中聲明變量用var,定義函數用function,
這個例子可以實現 愛好的驗證(不能為空) ,密碼是否一致,而且密碼的長度要大于8,備注是否為空!
另外,css文件就交給讀者自己美化了~
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答