一个简单的页面校验

 

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Validate Demo</title>
<style>
td{
padding-left:5px;
font-size:12px;
}
.red{
color:red;
padding-left:10px;

}

</style>
</head>

<body>
<form name="form1" method="post" action="">
  <table width="500"  border="0" align="center" cellspacing="1" bgcolor="#CCCCCC">
   
    <tr bgcolor="#FFFFFF">
      <td width="100">Text01</td>
      <td width="300"><input name="a1" type="text" id="a1"></td>
      <td>&nbsp;</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td>Text02</td>
      <td><input name="a2" type="text" id="a2"></td>
      <td>&nbsp;</td>
    </tr>
    <tr bgcolor="#FFFFFF" align="center">
      <td colspan="3"><input type="button" name="Submit" value="DoCheck" onClick="doCheck()"></td>
    </tr>
  </table>
</form>



<script>

function doCheck()
{
   var t=document.all;
    clearAllErr();
    alert("will Start to check.....")
	if(t.a1.value=="")
	{
	addErr(t.a1,"不能为空");
	}
	
	if(t.a2.value=="")
	{
	addErr(t.a2,"不能为空");
	}


}

/**
**
*清除所有错误信息
*
*/
function clearAllErr()
{

	var tt = document.all.errspans;
	if(!IsJsObject(tt)) return ;
	 
	if(tt.length > 1)
	{
	
		for(var i=0;i<tt.length;i++)
		{
			tt[i].innerHTML = "";
		}
	}
	else
	{
		tt.innerHTML = "";
	}

}

 
/**
**
*增加错误信息
*@fieldName 输入框id
*@mesg 错误信息
*/
function addErr(fieldName, mesg)
{
	var newElement = document.createElement("SPAN");
	newElement.className = "red";
	newElement.id = "errspans";
	newElement.name = "errspans";
	
	if(fieldName.parentNode.lastChild.name != "errspans")
	{
		fieldName.parentNode.appendChild(newElement);
	}
	if(fieldName.parentNode.lastChild.innerHTML == "")
	{
		fieldName.parentNode.lastChild.innerHTML = mesg;
	}
}

/*
 *功能:判断是否输入参数对象是否存在
 *参数:对象本身,比如document.all.inputName
 */
function IsJsObject(obj)
 {
	try
	{
		if(typeof(obj) == 'object')
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	catch(e)
	{
		//alert(e.message);
		return false;
	}
}

</script>
</body>
</html>

 

你可能感兴趣的:(校验)