March 15, 2011

Struts 1.x - Validator Framework Example

We shall replace the validate() method in this example - with the Validator Framework

In addition to the Struts 1.3.8 jars and the Apache Commons jars, also add the Jakarta-Oro jar into the lib folder of your application. Download the oro jar from here

1) Change the file to make the LoginForm class extend from the ValidatorForm class instead of the ActionForm class. Also remove the validate() method from the LoginForm class.

public class LoginForm extends ValidatorForm {

2) Modify the struts-config.xml file to add the <plug-in> element,

   <message-resources parameter="ApplicationResources" />

   <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
      <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml,/WEB-INF/validation.xml"/>

3) Add a new validation.xml file to the WEB-INF folder of the web application, as below. This configuration will validate the username and password fields for required field validation and also for the form input to comply/match the regular expressions.

<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"


      <form name="loginForm">
         <field property="username" depends="required,mask">
            <arg position="0" key="username.required"/>
         <field property="password" depends="required,mask">
            <arg position="0" key="password.required"/>
            <msg name="mask" key="password.maskmsg" />

4) In the message resources bundle, the file, add the following messages,

# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.{0} is not a date.
errors.range={0} is not in the range {1} through {2}.{0} is an invalid credit card number.{0} is an invalid e-mail address.

password.maskmsg=Password should be of length between 8 and 15 characters

5) Open the following URL in the browser and test for required field validation as well as form field input validation that complies with the regular expressions in the validation.xml


No comments:

Post a Comment