提交表单时验证

<!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=gb2312" />
<title>测试页面</title>
<script type="text/javascript">
function checkform(){
  //验证用户名
  if($("username").value == ""){
    $("n_msg").innerHTML ="用户名不可以为空";
    $("username").select();
    $("username").focus();
    return false;
  }else{
    if($("username").value.length < 6){
      $("n_msg").innerHTML = "用户名必须大于6个字符";
      $("username").select();
      $("username").focus();
      return false;
    }
  }
  //验证密码
  if($("password").value == ""){
    $("p_msg").innerHTML ="密码不可以为空";
    $("password").select();
    $("password").focus();
    return false;
  }else{
    if($("password").value.length < 10){
      $("p_msg").innerHTML = "密码必须大于10个字符";
      $("password").select();
      $("password").focus();
      return false;
    }
  }
  //.....(下面的可以以此类推)
  return true;
}

function $(id){
  return document.getElementById(id);
} 
</script>
<style type="text/css">
body{ font:12px 宋体}
.c_red{ color:#f00}
</style>
</head>

<body>
<table width="500" border="0" cellspacing="0" cellpadding="0">
 <form method="post" onsubmit="return checkform()">
  <tr>
    <td width="89">用户名</td>
    <td width="223"><input name="username" type="text" id="username" /></td>
    <td width="188" id="n_msg" class="c_red"></td>
  </tr>
  <tr>
    <td>密码</td>
    <td><input name="password" type="password" id="password" /></td>
    <td id="p_msg" class="c_red"></td>
  </tr>
  <tr>
    <td colspan="3"><input name="sub" type="submit" id="sub" value="提交" /></td>
  </tr>
  </form>
</table>

</body>
</html> 

===========================
posted @ 2012-11-02 10:09  yuloe2012  阅读(202)  评论(0编辑  收藏  举报