yanhaolang 发表于 2008-2-2 17:43

我的 验证函数不能验证表单 ,请高手看看

简单的表单验证,竟然出错,看不出哪里错?
后发现 我如果不用f=document.form1,而直接document.form1.username.value
document.form1.password.value,  ....就正常,这是为什么呢?
我以前 是用f=document.form1 这个去代替那些重复用的部分,写的验证 都正常啊,
今天 摆弄了一下午, 请高手指点。。。。
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.sql.*,javax.swing.*" %>
<%
String username=request.getParameter("username");
String password=request.getParameter("password");
String safecode=request.getParameter("safecode");
if(username!=null&&password!=null){
  session.setAttribute("username",username);
  session.setAttribute("password",password);
  session.setAttribute("safecode",safecode);
  if(safecode.equals(session.getAttribute("rand"))){
    response.sendRedirect("check.jsp");

  }
  else{
    out.print("<script language='javascript'>alert('验证码错误!');"+
    "return false;</script>");
  }

}




%>
<html>
<head>
<title>
login
</title>
<link href="images/my_css.css"  rel="stylesheet" type="text/css">

<script language="javascript">
var f=document.form1;
function check_login(){
        if(f.username.value=="" || f.password.value=="")
        {
         alert("用户名或密码不能为空!");

         f.username.focus();
         return false;
         }
        if(f.safecode.value==""){
        alert("请输入验证码!");
        f.safecode.focus();
        return false;
        }
        return true;
}
</script>








</head>
<body bgcolor="#ffffff">
<table width="299" border="0" align="center">
  <tr class="version">
    <td height="25" colspan="2" align="center" valign="middle" class="my_title1">登 陆</td>
  </tr>
  <form name="form1" action="login.jsp" onSubmit="return check_login()" method="post">
  <tr>
    <td width="96" height="28" align="center" valign="baseline" class="version">用户名:</td>
    <td width="193" height="28"><input name="username" type="text" class="my_input3" id="username"></td>
  </tr>
  <tr>
    <td height="28" align="center" valign="baseline" class="version">密&nbsp; 码:</td>
    <td height="28"><input name="password" type="password" class="my_input3" id="password"></td>
  </tr>
  <tr>
    <td height="28" align="center" valign="middle" class="version">认证码:</td>
    <td height="28">&nbsp;</td>
  </tr>
  <tr>
    <td height="28" align="center" valign="baseline" class="version">认证码:</td>
    <td height="28" valign="middle"><input name="safecode" type="text" class="my_input3" id="safecode"></td>
  </tr>
  <tr class="version">
    <td height="28" colspan="2" align="center"><input type="submit" name="Submit" value="提交">&nbsp;&nbsp;
      <input type="reset" name="Submit2" value="重置"></td>
  </tr>
  </form>
</table>

</body>
</html>

hwoarangzk 发表于 2008-2-2 17:45

因为你先就把var f=document.form1定义了,但是此时页面还没有完成加载,就是说这个时候还没有form1。之后页面加载完成后,你再调用函数的,当然能找到form1了

hwoarangzk 发表于 2008-2-2 17:46

你可以试试把var f=document.form1放在function check_login()里面的第一句就知道为什么了

yanhaolang 发表于 2008-2-2 17:53

知道了,谢谢!

页: [1]

编程论坛