[ Team LiB ] |
![]() ![]() |
Recipe 12.6 Using JavaScript to Validate Form Values in a JSPProblemYou want to import JavaScript into a JSP to validate HTML form values. SolutionUse 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. DiscussionThe 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 AlsoThe 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. |
[ Team LiB ] |
![]() ![]() |