Tutorials : Applying Design Patterns to Your Struts Validation Framework :

The First Solution: Overwriting the ValidatorForm's validate Method

The Struts Validator Framework uses two XML configuration files:
  1. validator-rules.xml: Defines the standard validation routines, which are reusable and used in validation.xml. to define the form specific validations.
  2. validation.xml: Defines the validations applied to a form bean.
If you don't implement a customized Struts validator, which is defined into the validator-rules.xml, you may overwrite the validate method (defined in the org.apache.struts.validator.ValidatorForm). This allows you to perform the extra validation logic inside the validate method. The class diagram is simple since no extra classes need to be created (see Figure 1).


Figure 1. Simple Personal Identity Validation Class Diagram

The example application in this article requires the following steps to meet the business validation requirements defined in Listing 1.

  1. Create PersonalIdentityForm.java: This class extends the ValidatorForm super class. Define two String type attributes (selectedPersonalIdentity and personalIdentityNumber) and its getter/setter methods.
  2. Create personalIdentityValidtion.jsp: This contains the validation form. It includes one drop drown list containing the various identity types (named as selectedPersonalIdentity) and an input box where the user inputs their identity number (named as personalIdentityNumber). Listing 2 shows the code for the form.
  3. Create the ValidatePersonalIdentity.java action class: This extends the org.apache.struts.action.Action super class. The execute method is implemented and performs the actual back-end business logic—including the identity number validation against the customer database and any other business logic based on the identity number validation result. In this example, the back-end logics are added inside the validatePersonalIdentity( String personalIdentity, String identityNumber) method (shown in Listing 3).
  4. Define <form-bean> for PersonalIdentityForm and <action> for ValidatePersonalIdentity's configuration setting in the struts-config.xml file:
    <form-bean name="personalIdentityForm"   
              type="com.abc.registration.form.PersonalIdentityForm"></form-bean>
    		  
    …..
    <action path="/validatePersonalIdentity" 
    	 type="com.abc.registration.action.ValidatePersonalIdentity"   
    	 name="personalIdentityForm" input="personalIdentityValidtion.jsp" 
    	 validate="true">			
    		<forward name="success" path="personalIdentityValidtion.jsp" />
    		<forward name="failure" path="personalIdentityValidtion.jsp" />
    	</action>
    
  5. Declare the struts basic build-in validation rule (required) for both properties (selectedPersonalIdentity and personalIdentityNumber) in the PersonalIdentityForm in the struts validation configuration file (validation.xml):
    <form name="personalIdentityForm">
              <field property="selectedPersonalIdentity" depends="required">         
    				 <arg0 key=
    				 "validator.selectedPersonalIdentity.required" />                  
              </field>
    		  <field property="personalIdentityNumber" depends="required">	        
    	          	 <arg0 key="validator.personalIdentityNumber.required" />
    				 </field>	      
         </form>
    	 
  6. Enable the ValidatorPlugin with config XML file names and declare the message resources file named ApplicationResources.properties under the resources and strutsvalidator directory, which contains the message key definition in the struts-config.xml file:
    <message-resources  parameter="strutsvalidator.resources.ApplicationResources" />
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    	<set-property property="pathnames" 
    	value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/>
    </plug-in>
    
  7. Overwrite the validate method in PersonalIdentityForm.java with the validation business logic based on Figure 1 (shown in Listing 4).

  8. Add the error message display in Listing 5 block into the JSP page at personalIdentityValidtion.jsp.
  9. Add all of the application message keys' definitions in the message resources file called ApplicationResources.properties and add them under the strutsvalidator/resources directoy within the classpath (Listing 6).
  10. Build the application and deploy it into the application server. This examples used the IBM WSAD 5.1 test environment server to do the test.
  11. Test the validation rules using the following scenarios:
    • The user does not select any type of Personal Identity Type and inputs a random number for their Personal Identity Number. Since both form properties are declared as "required" fields, the default message key has been used (errors.required={0} is required.). {0} will be replaced by the parameter valued of validator.selectedPersonalIdentity.required and validator.personalIdentityNumber.required. These results are shown in Figure 2.


      Figure 2. The "Required" Validation Rule Defined in validation.xml

    • The user selects the ABC PIN and inputs the PIN number as abc123 which is less than its minimum length requirement (10). The results are shown in Figure 3.


      Figure 3. The Minimum Length Validation Rule

    • The user selects the ABC PIN and inputs the PIN number as 1234567890abc which is greater than its maximum length requirement (10). The results are shown in Figure 4.


      Figure 4. The Maximum Length Validation Rule

    • The user selects the ABC PIN and inputs the 1234567890 which does not match the pattern of the ^([A-Z]{1}[-]{1}[A-Z0-9]{3}[-]{1}[A-Z0-9]{4})$ i.e. x-xxx-xxxx format (X is either A-Z or 0-9, but the first character must be character, i.e. A-Z). The results are shown in Figure 5.


      Figure 5. The Mask Validation Rule

    • The user selects the ABC PIN and inputs the >A-4P6-58DF, which meets all of the ABC PIN data format validation rules, i.e. minimum length, maximum length, and mask. If this number is the same as what the customer's REAL data, which stores in ABC Wireless Inc's database, then they will see the "Personal Identity Validation Result" message with the "Your personal identity number validation is successful." message and then the "Continue Your Registration" button allows them to continue the online self-registration process. The results are shown in Figure 6.


      Figure 6. The User's Input Data Meets the Entire Validation Rules

    • The user enters X-4P6-FFXX, which has the correct format of the ABC PIN number, but it is not the validated ABC PIN number issued by ABC Wireless. in this case, the back-end validation fails and the user sees the specific error message ("Your personal identity number validation is failed. Please try it again (Figure 7).


      Figure 7. The error message is shown even though the input PIN number has correct PIN format; the actual number is still not correct when the PIN number’s back-end validation failed.

    • You can also perform validation tests for all of the other personal identity types (drivers license, immigration number, social security number, passport number, etc.).

      This approach is relatively straightforward and easy to implement. However, the validation rules for personal identity number, and the error message key names are ALL hard-coded into the Java source code.

If you should later decide to make any of the following changes, you'll need to rewrite the validate method in PersonalIdentityForm.java:
  1. Add/remove an identity type from the business requirement.
  2. Change the error message key names.
  3. Change any validation rule (minimum length, maximum length and mask) any of the personal identity types.
These types of changes are error-prone and might cause errors. The PersonalIdentityForm class cannot be closed, but you can open it for modification.

Home / Articles / Applying Design Patterns to Your Struts Validation Framework / 1 / 2 / Next Page

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.