Recipe 12.6 Using JavaScript to Validate Form Values in a JSP


Problem

You want to import JavaScript into a JSP to validate HTML form values.

Solution

Use the c:import JSTL core tag to import the JavaScript function definitions. Then validate the HTML form input by using the form tag's onSubmit event handler.

Discussion

The JSP in Example 12-8 uses the JSTL core tag c:import to include the contents of the /WEB-INF/javascript/validate.js file. See Example 12-6 for the contents of validate.js , which is a definition for the function validate . This function determines whether the user has left any form fields blank.

The rest of the JSP is straightforward: the onSubmit event handler calls the validate function and passes in the form object (represented by the JavaScript keyword this ) as a parameter. By returning false , the validate function cancels the form submit if it finds any blank fields.

Example 12-8. A JSP uses JavaScript to validate HTML form input
  <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  <html> <head>  <c:import url="/WEB-INF/javascript/validate.js" />  <title>Help Page</title></head><body> <h2>Please submit your information</h2>  <form action ="/home/displayHeaders.jsp" onSubmit=" return validate(this)">  <table border="0"><tr><td valign="top"> Your name: </td>  <td valign="top"> <input type="text" name="username" size="20"> </td></tr><tr><td valign="top"> Your email: </td>  <td valign="top"> <input type="text" name="email" size="20"> </td></tr> <tr><td valign="top"> <input type="submit" value="Submit Info"></td></tr> </table></form> </body></html> 

Figure 12-4 shows the web page containing the form. Figure 12-5 depicts the alert window that would be displayed if the user leaves one or more text fields blank when submitting the form.

See Also

The Netscape DevEdge site at http://devedge.netscape.com/; Recipe 12.2 and Recipe 12.4 on using JavaScript with JSPs to import JavaScript function definitions and create new browser windows ; Recipe 12.3 on creating new browser windows with servlets and JavaScript; Recipe 12.5 on validating form values with a servlet and JavaScript; Recipe 18.3 on using a filter with HTTP requests .



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net