2013-05-01 38 views
0

下面是我的JSP文件,我是用servlet来检查,如果字段为空,但显然这需要在客户端完成。当按下提交按钮并且一个字段为空时,如何阻止提交表单?如何防止我从形式提交如果字段为空(JSP)?

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%> 
<%@ page session="false" %> 
<!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=ISO-8859-1"> 
<style type="text/css"> 
h1 { font-family : cooper black;} 
</style> 
<title>Add a Phonebook Entry</title></head> 
<body> 
<h1> Add a Phonebook Entry</h1> 
<form action="process.do" method="GET"> 
<table summary="phonebook entry table"> 
    <tr> 
     <td>Last name:</td> 

     <% 
     String last = ""; 
     String first = ""; 
     String phone = ""; 

     if(request.getParameter("surname")!=null){ 
      last = (String) request.getParameter("surname"); 
     } 
     if(request.getParameter("firstname")!=null){ 
      first = (String) request.getParameter("firstname"); 
     } 

     if(request.getParameter("phone")!=null){ 
      phone = (String) request.getParameter("phone"); 
     } 
     %> 

     <td><input type="text" title="enter your last name here" name="surname" name="initials" size=10 maxlength=10 value=<%= last %> ></td> 
    </tr> 
    <tr> 
     <td>First name:</td> 
     <td><input type="text" name="firstname" size=10 maxlength=10 value=<%=first %> ></td> 
    </tr> 
    <tr> 
     <td>Phone number: </td> 
     <td><input type="text" name="phone" maxlength=10 size=10 value=<%=phone %> > </td> 
    </tr> 
</table> 
<br><input type="submit" value="Submit"> 
</form> 
<p> View the phonebook <a href="./Display.jsp">here</a></p> 

回答

2

的JavaScript

基本上具有短的脚本,其检查所有的输入被填充。如果不是,则阻止提交请求。

你仍然要执行一些服务器端检查字段,用户可以禁用JavaScript的。我的以下建议也一样。

HTML5

还有必要的HTML5特性。 我不认为这是在所有的浏览器都支持呢。

<input type="text" name="username" required> 

如果未填充并且启用了HTML5验证,表单将不会提交。

+0

谢谢你,需要的属性正是我一直在寻找。 – otis92 2013-05-01 15:21:50

1

那一小块的JavaScript的可能是,使用jQuery:

$("#form").submit(function() { 
    var requiredFailed = true; 
    $("#form input:text").each(function() { 
     if ($.trim($(this).val()).length == 0) { 
      requiredFailed = false; 
      return false; 
     } 
    }); 
    return requiredFailed; 
}); 

它看上去通过文本类型的所有输入,如果任何输入将是空的,表单就不会被提交。

0

尝试以下方法...应该工作remeber的<%......%>

out.print("Please enter "); 
if(fieldname.length()==0){ 
    out.print("field name"); 
} 
if (fieldname2.length()==0) { 
    out.print(" and "); 
} 
if (fieldname2.length()==0){ 
    out.print("field name2"); 
} 
out.println("breakline");