我們在做開發(fā)時,經(jīng)常要做表單驗證,比如驗證文本框必須填內(nèi)容時,而文本框又很多時,傳統(tǒng)的做法是逐個判斷: if (form1.name.value == "") { alert("Sorry,please input your name!") form1.focus(); } 這樣一來要寫的代碼太多了,有沒有“偷懶”的方法呢,答案是肯定的,請看下面的代碼:
代碼如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml"> <head> <title>“偷懶”的表單驗證Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <meta name="Generator" content="EditPlus" /> <meta name="Author" content="Dicky"> <meta name="Keywords" content="Name:Dicky;QQ:25941;MSN:HaiJunGu@HotMail.Com"> <meta name="Description" content="Name:Dicky;QQ:25941;MSN:HaiJunGu@HotMail.Com"> <script language="javascript" type="text/javascript"> <!-- //剪去字符串內(nèi)的所有空格 function JsTrim(str) { var newstr = "" for(var jj = 0;jj < str.length;jj ++) { var tmpstr = str.substring(jj,jj+1); if (tmpstr != " ") { newstr = newstr + tmpstr; } } return newstr; } function CheckForm() { var obj = document.body.getElementsByTagName("input"); //列出所有標簽為input的集合 for (var mm = 0; mm < obj.length; mm++) { if ((obj[mm].getAttribute("type") == "text") && (obj[mm].getAttribute("name") != "Address")) //不檢查Address是否輸入 { if (JsTrim(obj[mm].value) == "") { window.alert(obj[mm].getAttribute("ErrorMsg")); //彈出錯誤提示語 obj[mm].focus(); obj[mm].select(); return false; } } } document.form1.submit(); } //--> </script> </head> <body> <form name="form1" method="post" onsubmit="return CheckForm(this);"> <div>Name:<input type="text" name="Name" errormsg="Sorry,please input your name!" /></div> <div>Sex :<input type="text" name="Sex" errormsg="Sorry,please input your sex!" /></div> <div>Age :<input type="text" name="Age" errormsg="Sorry,please input your age!" /></div> <div>Addr:<input type="text" name="Address" /> <div><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Reset" value="Reset" /></div> </form> </body> </html> |
|