2013-05-01 46 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");