我们在做开发时,经常要做表单验证,比如验证文本框必须填内容时,而文本框又很多时,传统的做法是逐个判断: if (form1.name.value == "") { alert("Sorry,please input your name!") form1.focus(); } 这样一来要写的代码太多了,有没有“偷懒”的方法呢,答案是肯定的,请看下面的代码:
代码如下:
<!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>
<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">
<!--
//剪去字符串内的所有空格
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>
[Ctrl+A 全选 提示:你可先修改部分代码,再点运行代码]