本文實(shí)例講述了JS實(shí)現(xiàn)的簡(jiǎn)單表單驗(yàn)證功能。分享給大家供大家參考,具體如下:
源代碼:
<!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>無(wú)標(biāo)題文檔</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" />愛(ài)好:<input type= "checkbox" name="ah" />爬山<input type= "checkbox" name="ah" />游泳<input type= "checkbox" name="ah" />網(wǎng)球<input type= "checkbox" name="ah" />乒乓球<br/>密碼:<input type="password" name="mm"/><br/>重復(fù)密碼:<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)//沒(méi)有一個(gè)愛(ài)好被選中{alert("請(qǐng)至少選擇一個(gè)愛(ài)好!");return;//假如沒(méi)有找到,又返回去,直到找到!}if(document.forms[0].mm.value.length<9){alert("密碼長(zhǎng)度必須在8位數(shù)以上!");document.forms[0].mm.focus();//讓密碼框獲取焦點(diǎn),焦點(diǎn)是 可以根據(jù)應(yīng)用配合完成一些自動(dòng)化操作,比如登錄時(shí)輸入了錯(cuò)誤的用戶(hù)名和密碼,回轉(zhuǎn)登錄頁(yè)后,可以讓用戶(hù)名輸入框自動(dòng)獲得焦點(diǎn),避免用戶(hù)重新定位。return;}if(document.forms[0].mm.value!=document.forms[0].cfmm.value){alert("兩次密碼輸入不一致,請(qǐng)重新輸入密碼!");return;}if(document.forms[0].bz.value==""){alert("請(qǐng)輸入備注!");}}注意:在js中聲明變量用var,定義函數(shù)用function,
這個(gè)例子可以實(shí)現(xiàn) 愛(ài)好的驗(yàn)證(不能為空) ,密碼是否一致,而且密碼的長(zhǎng)度要大于8,備注是否為空!
另外,css文件就交給讀者自己美化了~
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答