日期:2014-05-17  浏览次数:20631 次

初学javaweb进行客户端验证练习遇到的问题
使用javascript编写函数对表单进行验证,当输入信息不符合时,用alert弹出警告窗口,并返回false不提交表单;而仅当输入信息都符合条件时,返回true提交表当。但遇到的一个问题,无论填写的信息正确与否,弹出警告窗后点击确定,表单总是会被提交。而且在form标签中使用这样的定义“<form onsubmit="return Validate">”,会提示这样的错误“Cannot return from outside a function or method.”。希望哪位高手会的帮忙解答下,感激....
代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'CheckTest.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function Validate()
{
var username=document.getElementById("username");
var password=document.getElementById("password");
var repassword=document.getElementById("repassword");
if(username.value.length ==0)
{
 alert("username can not be blank!!!");
 return false;
}
if(password.value.length ==0)
{

 alert("password can not be blank!!!");
 return false;
}
if(repassword.value.length ==0)
{
 alert("repassword can not be blank!!!");
 return false;
}
if(password.value!=repassword.value)
{
 alert("The two password are not same!!!");
 return false;
}

return true;
 }
</script>

<style type="text/css">

label{
width:90px;
float:left;
}
</style>
  </head>
  
  <body>
      <form onsubmit="return Validate()" action="CheckServlet">
       <label for="username">用户名:</label><input type="text" name="username" id="username"/><br/>