Creating Your Own Validation Rules

The Validator framework is preconfigured with many of the most common rules that you’re likely to need for your Struts applications. If your application has validation requirements that are not met by the default rules, you have complete freedom to create your own. There are several steps that you must follow, however, to create your own customized rules:

  1. Create a Java class that contains the validation methods.

  2. Edit the validation-rules.xml file or create your own version. If you do create a new validation resource file, be sure to add it to the list of resource files in the Validator plug-in.

  3. Use the new validation rules in the validation.xml file for your application.

Each validation method you create must have the following signature:

public static boolean validateXXX( java.lang.Object,
                                   org.apache.commons.validator.ValidatorAction,
                                   org.apache.commons.validator.Field,
                                   org.apache.struts.action.ActionErrors,
                                   javax.servlet.http.HttpServletRequest,
                                   javax.servlet.ServletContext );

where validateXXX can be whatever you want it to be, as long as it’s not a duplicate rule name. Table 11-3 explains the arguments to the validateXXX( ) method.

Table 11-3. The validateXXX( ) method arguments

Parameter

Description

Object

The JavaBean on which validation is being performed

ValidatorAction

The current ValidatorAction being performed

Field

The field object being validated

ActionErrors

The errors objects to add an ActionError to if the validation ...

Get Programming Jakarta Struts 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.