Home > Articles > Programming > Java

Java Reference Guide

Hosted by

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Server-side Form Validation

Last updated Mar 14, 2003.

If you’re looking for more up-to-date information on this topic, please visit our Java article, podcast, and store pages.

One of the more important features in Struts is its support for form validation. Form validation comes in two flavors:

  • Server-side Validation
  • Client-side Validation

Server-side validation allows you to validate the contents of a form inside your Java form class running in your application server, whereas client-side validation allows form contents to be validated using JavaScript at the browser before the request is ever forwarded to your application server. Some types of validation are better suited to be performed in your application server, but whenever possible it is better to validate form contents on the client. After all, if your users are interacting with your web application, they have more CPU cycles to spare than your application server does.

Starting with server-side validation, Struts performs server-side validation by calling your ActionForm's validate() method. Before calling your validate() method, Struts invokes all appropriate setXXX() methods to initialize your form parameters (ActionForm bean properties.) The validate() method is passed two parameters: an ActionMapping instance and the HttpServletRequest for the request, and is responsible for returning an ActionErrors object. The method signature is defined as follows:

ActionErrors validate( ActionMapping mapping, HttpServletRequest request )

A successful validation returns either a null value or a zero-length ActionErrors instance. If an error occurs then you need to construct one or more ActionMessage instances that describe the nature of the problem and associate it with the offending form parameter. The ActionMessage is built by passing it a key and optional values into a Struts message resources properties file.

The message resources property file is referenced in the struts-config.xml file by the <messages-resource> node. By default this file is named MessageResources.properties file and resides directly in your src/java folder. But depending on what IDE you are using, this value is subject to change. This file contains localized strings to support internationalization: rather than directly printing text in your web pages, you can use the <bean:message> Struts tag to load the localized text from a properties file. A final note on this file, each string can contain parameters denoted by {0}, {1}, etc. that you can fill in with contextual data.

The steps therefore to implement server-side form validation are as follows:

  1. Add the validate() method to your ActionForm
  2. Validate the meaningful form parameters in the validate() method
  3. If there are errors then construct an ActionErrors instance and ActionMessage instances for each error, associating the ActionMessage with the offending form parameter
  4. Add message keys and values to your message resources properties file that are referenced by your ActionMessages
  5. Return the ActionErrors object
  6. Modify your view component (JSP file) by adding an <html:errors/> tag (this displays the error message(s))

As an example, consider the following registration form:

Listing 1. register.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Register</title>
 </head>
 
 <body>
 
 <html:errors/>

 <html:form action="register">
  <table border="0" width="90%" align="center">
   <tbody>
    <tr>
     <td align="right"><bean:message key="register.firstName"/></td>
     <td><html:text property="firstName" maxlength="64" size="20" /></td>
    </tr>
    <tr>
     <td align="right"><bean:message key="register.lastName"/></td>
     <td><html:text property="lastName" maxlength="64" size="20" /></td>
    </tr>
    <tr>
     <td align="right"><bean:message key="register.email"/></td>
     <td><html:text property="email" maxlength="64" size="20" /></td>
    </tr>
    <tr>
     <td align="right"><bean:message key="register.login" /></td>
     <td><html:text property="login" maxlength="64" size="20" /></td>
    </tr>
    <tr>
     <td align="right"><bean:message key="register.password" /></td>
     <td><html:password property="password" maxlength="64" size="20" /></td>
    </tr>
    <tr>
     <td align="right"><bean:message key="register.confirmPassword" /></td>
     <td><html:password property="confirmPassword" maxlength="64" size="20" /></td>
    </tr>
    <tr><td colspan="2" align="center"><html:submit value="Register" /></td></tr>
   </tbody>
  </table>
  
 </html:form>
 
 </body>
</html>

This registration form begins with a <html:errors/> tag. The purpose of this tag is to display all error messages that are generated by the ActionForm's validate() method: if there are no errors then this tag will be ignored, but if there is a problem then it will list every field that failed validation and its corresponding localized string. Each field in the form loads its label from the message resources file by using the <bean:message> tag and passing it the appropriate key. A corresponding MessageResources.properties file is shown in listing 2.

Listing 2. MessageResources.properties

errors.header=<UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It’s easy to create Struts applications with NetBeans.
errors.firstName.required=You need to enter your first name
errors.lastName.required=You need to enter your last name
errors.password=Your password and confirmation password do not match or are invalid
register.firstName=First Name
register.lastName=Last Name
register.email=Email Address
register.login=Login Name
register.password=Password
register.confirmPassword=Confirm Password
header.news=News
header.forums=Forums
header.articles=Articles
header.toolbox=Toolbox
header.education=Education
header.about=About

Therefore, when the registration form references <bean:message key="register.firstName">, it is replaced by the string "First Name." The properties file can then be localized for other languages.

Listing 3 shows the accompanying ActionForm bean that performs the validation.

Listing 3. RegisterActionForm.java

package com.javasrc.struts;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class RegisterActionForm extends org.apache.struts.action.ActionForm {
 
 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if (getFirstName() == null || getFirstName().length() < 1) {
   errors.add("firstName", new ActionMessage("error.register.firstName.required"));
  }
  if (getLastName() == null || getLastName().length() < 1) {
   errors.add("lastName", new ActionMessage("error.register.lastName.required"));
  }
  if( this.password == null || !this.password.equals( this.confirmPassword ) ) {
   errors.add( "password", new ActionMessage( "error.register.password" ) );
  }
  return errors;
 }
 
 private String firstName;

 public String getFirstName() {
  return this.firstName;
 }
 
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 
 private String lastName;
 
 public String getLastName() {
  return this.lastName;
 }
 
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 
 private String email;
 
 public String getEmail() {
  return this.email;
 }
 
 public void setEmail(String email) {
  this.email = email;
 }
 
 private String password;
 
 public String getPassword() {
  return this.password;
 }
 
 public void setPassword(String password) {
  this.password = password;
 }
 
 private String confirmPassword;
 
 public String getConfirmPassword() {
  return this.confirmPassword;
 }
 
 public void setConfirmPassword(String confirmPassword) {
  this.confirmPassword = confirmPassword;
 }
 
 private String login;
 
 public String getLogin() {
  return this.login;
 }
 
 public void setLogin(String login) {
  this.login = login;
 }
}

When the form is submitted to Struts, it creates a new RegisterActionForm instance, calls its setXXX() methods to initialize its properties, and then calls the validate method. If the form does not contain a first or last name, or if the password does not match the confirmation password, then the validate() method returns a populated ActionErrors object, otherwise it returns an empty object. If the ActionErrors object is populated then the request is forwarded back to the JSP file that submitted it in the first place (register.jsp), but the <html:errors/> is replaced with a list of error messages, such as the following:

 <h3><font color="red">Validation Error</font></h3>You must correct the following error(s) before proceeding:
 <ul>
  <li>You need to enter your first name</li>
  <li>Your password and confirmation password do not match or are invalid</li>
 </ul><hr />

Once the user's request satisfies your validation requirements, the ActionForm is passed to your Action's execute() method and processing can continue.