7.4 Performing Presentation Validation

This chapter has touched on performing your application's input validation in the validate( ) method of the ActionForm. You can create whatever presentation validation rules you need in this method. For example, the LoginForm from Example 7-2 validated that the email and password fields were entered and were not empty strings. Although this is a trivial example, you can validate anything you like. A common validation rule is to ensure that a string value that should be a number is in fact a string representation of a valid number. The validate( ) routine for this rule might look like the one in Example 7-5.

Example 7-5. Performing a number validation rule
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
  ActionErrors errors = new ActionErrors(  );
 
  String orderQtyStr = getQuantity(  );
 
  if( orderQtyStr == null || orderQtyStr.length(  ) < 1 ){
    errors.add( ActionErrors.GLOBAL_ERROR,
                new ActionError( "order.quantity.required" ));
  }
 
  // Validate that the qty entered was in fact a number
  try{
    // Integer.parse was not used because it's not really I18N-safe
    java.text.Format format = java.text.NumberFormat.getNumberInstance(  );
    Number orderQty = (Number)format.parseObject( orderQtyStr );
  }catch( Exception ex ){
    // The quantity entered by the user was not a valid qty
    errors.add( ActionErrors.GLOBAL_ERROR,
                new ActionError( "order.quantity.invalid" ));
  }
  return errors;
}

As you can imagine, web applications often need to check for required values or validate that data entered fits a certain format or is of a certain type. Because all data that is retrieved from a request is of type String, you must ensure that the data is not going to corrupt your business components.

Although you can perform the validation programmatically, the Struts framework provides an alternative that can be external to the ActionForm and the validate( ) method. In fact, most of the standard validation rules already are defined, so you don't have to write any code for them. All you need to do is to declaratively configure the rules that you need in an extra XML file. The Struts Validator will be covered in Chapter 11.