Validator enables you to use client side validation using JavaScript without having to write the JavaScript validation functions yourself. All you need to do is include the javascript element of the Struts HTML Tag Library and add an onsubmit event handler in the form element.
The app05b application shows off the client side validation in Validator. This application is based on the app05a application and all you need to change is the displayAddOrderForm.jsp page, which is given in Listing 5.3.
Listing 5.3: The displayAddOrderForm.jsp page
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html>
<head>
<title>Add Order Form</title>
<html:javascript formName="orderForm"/>
</head>
<body>
<html:errors/>
<html:form action="/saveOrder"
onsubmit="return validateOrderForm(this)">
<table>
<tr>
<td>Product:</td>
<td>
<html:select property="productId">
<html:option value="1">Monitor</html:option>
<html:option value="2">Keyboard</html:option>
<html:option value="3">Mouse</html:option>
</html:select>
</td>
</tr>
<tr>
<td>Customer:</td>
<td><html:text property="customer"/></td>
</tr>
<tr>
<td>Quantity:</td>
<td><html:text property="quantity"/></td>
</tr>
<tr>
<td>Price:</td>
<td><html:text property="price"/></td>
</tr>
<tr>
<td>Order Date: (mm/dd/yyyy)</td>
<td><html:text property="orderDate"/></td>
</tr>
<tr>
<td><html:submit>Ok</html:submit></td>
<td><html:cancel>Cancel</html:cancel></td>
</tr>
</table>
</html:form>
</body>
</html>
The javascript element generates the functions for client side validation of an action form. You must specify the logical name of an action form in the element’s formName attribute. Feel free to view the JavaScript script generated for the JSP to see the output of the javascript element.
To “link” the form with the generated JavaScript function, you must use the onsubmit attribute of the form element:
<html:form action="/saveOrder" onsubmit="return validateOrderForm(this)">
Run the app05b application by directing your browser to this URL.
http://localhost:8080/app05b/displayAddOrderForm.do
You will see the Add Order form in your browser. If you click the submit button before completing the form, you will see a popup window like the one in Figure 5.2, assuming of course, that the JavaScript feature in enabled in your browser.
Figure 5.2: The client side validation feature in Validator