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( ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage( "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( ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage( "order.quantity.invalid" ));
  }
  return errors;
}

As you can imagine, web applications often need to ...

Get Programming Jakarta Struts, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.