Field Validation

I l @ ve RuBoard

This code is still lacking a bit. First, if the customer enters a duplicate e-mail address, the page does not provide any helpful feedback to let him know that it occurred. Second, because you're not validating the fields, someone could put total garbage into them and still create a new customer. Form-field validation is one of the major components of Web site design. You need to thoroughly understand what values are allowed in certain fields and how fields could be interdependent ”in other words, Field 1 might be required only if Field 2 is filled in.

Validating fields is generally straight-forward. Returning error messages from validation is more complex and requires some decisions to be made. Basically, error conditions can be returned from validation in three ways; we'll consider each in turn .

Returning Errors in a Simple Vector

The most basic way to return error conditions is to have a single Vector property on the object being validated , called something like validationErrors . You add strings describing each validation error as you encounter them. You then put into the form a piece of JSP that looks like this:

 <%    Iterator errors = newcust.getValidationErrors().iterator();    while (errors.hasNext()) {       %>         Error: <%= errors.next() %><BR> <%       } %> 

This will cause all the errors discovered to display just above the form, one after another.

Unique Error Properties

Over time, experience has shown that users have an easier time if you display the errors near the field that caused them, especially in long forms. This leads to the second technique: tying a read-only validation error property to each field that get sets by the validation method. You would use it as follows :

 e-Mail Address: <INPUT NAME="email" TYPE="TEXT" SIZE=50        VALUE="<%= newcust.getEmail() %>">        <FONT COLOR="#FF0000"><%= newcust.getEmailValidationError() %></FONT><BR> 

This results in a red error message being displayed next to the field, if present. It's a bit clumsy to code, however, because it requires adding a separate validation error accessor for each field in the form, which can add quite a bit of bulk to your Java source. This method also requires you to manually clear each field.

Using a HashMap for Errors

A technique that might work better is to provide a single HashMap to hold the error messages with a single accessor function. Listing 8.8 has the additional source in the Java, and Listing 8.9 shows how it's used in the JSP.

Listing 8.8 Additions to Customer.java
 import java.util.HashMap; . . .     private HashMap validationErrors = new HashMap();     public String getFieldError(String fieldname) {       return((String)validationErrors.get(fieldname));     }     public void addFieldError(String fieldname, String error) {       validationErrors.put(fieldname, error);     }     public boolean validateCustomer() {       validationErrors.clear();       boolean valid = true;       if ((email == null)            (email.length() == 0)) {           addFieldError("email", "e-Mail Address is required.");           valid = false;       } else {           if (email.indexOf("@") == -1) {               addFieldError("email", "Please supply a valid address.");               valid = false;           }       }       if ((password == null)            (password.length() == 0)) {           addFieldError("password", "Password is required.");           valid = false;       }       return valid;     } 

The interesting thing to note here is that, because only one error message per field is allowed under this scheme, you want to make sure that the validation code doesn't check for an "@" unless the e-mail address is not blank. Otherwise, it will always set the "valid address" error, even on a blank field.

Listing 8.9 The revised NewCustomer.jsp
 <%@ page import="com.bfg.customer.Customer" %> <jsp:useBean id="newcust" class="com.bfg.customer.Customer" scope="request"/> <jsp:setProperty name="newcust" property="*"/> <% if (request.getParameter("SUBMITTED") != null) {     try {       if (newcust.validateCustomer()) {           newcust.createCustomer();           response.sendRedirect("NewSuccess.jsp");       }     } catch (com.bfg.exceptions.DuplicateEmailAddressException e) {      newcust.addFieldError("email",                             "e-Mail address already in use. <BR>" +                             "Click <A HREF=\"lostPassword.jsp\">here</A> "+                             "if you have forgotten your password.");     } } if (newcust.getEmail() == null) {     newcust.setEmail(""); } if (newcust.getPassword() == null) {     newcust.setPassword(""); } %> <HEAD><TITLE>Create New Customer Account</TITLE></HEAD><BODY> <FORM METHOD=POST ACTION="NewCustomer.jsp"> <INPUT TYPE="HIDDEN" NAME="SUBMITTED" VALUE="T"> <% if (newcust.getFieldError("email") != null) { %> <FONT COLOR="#FF0000"><%= newcust.getFieldError("email")%></FONT><BR> <% } %> e-Mail Address: <INPUT NAME="email" TYPE="TEXT" SIZE=50        VALUE="<%= newcust.getEmail() %>"><BR> <% if (newcust.getFieldError("password") != null) { %> <FONT COLOR="#FF0000"><%= newcust.getFieldError("password")%></FONT><BR> <% } %> Password: <INPUT NAME="password" TYPE="TEXT" SIZE=50        VALUE="<%= newcust.getPassword() %>"><BR> <INPUT TYPE=SUBMIT> </FORM> </BODY> 

The first change made is to add a call to validateCustomer and to conditionalize trying to call createCustomer by the success of the validation.

In a more clever solution, you can use the same error-reporting mechanism to display the error for a duplicate e-mail address, including a link to a page that handles reminders for lost passwords.

Now you can place a conditional display of the error message above each field, nicely highlighted in red. If you look at Figures 8.1 and 8.2, you can see the results of trying to submit a blank form and an error generated for a previously used address.

Figure 8.1. A blank form submission.

graphics/08fig01.jpg

Figure 8.2. Trying a duplicate e-mail address.

graphics/08fig02.jpg

I l @ ve RuBoard


MySQL and JSP Web Applications. Data-Driven Programming Using Tomcat and MySQL
MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL
ISBN: 0672323095
EAN: 2147483647
Year: 2002
Pages: 203
Authors: James Turner

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