O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required