Input Validation Using Jakarta Commons Validator

Applicable to: Commons Validator v1.2.7

The Validator framework is an open source project and is part of the Jakarta Commons subproject. Though the validator was originally designed for the struts framework, it can be easily plugged into other frameworks as well.

With this framework, no code needs to be written for all the common and built-in validations that come pre-packaged. All the validations are specified in xml files. New and application specific validations can also be written once and re-used through out the application.

Some of the validations that exist as part of the core validator framework include

required: mandatory field validation.
validwhen: validator for checking one field against another.
minlength: Data is not less than the minimum length specified.
maxlength: Data length does not exceed the maxlength specified.
mask: validate format according to a regular expression.
byte: validates that a field can be converted to a Byte.
short: validates that a field can be converted to a Short.
integer: validates that a field can be converted to an Integer.
long: validates that a field can be converted to a Long.
float: validates that a field can be converted to a Float.
double: validates that a field can be converted to a Double.
date: validates that a field can be converted to a Date.
creditCard: succeeds if the value could be a valid credit card number.
email: succeeds if the value could be a valid e-mail address.

The validator supports internationalization by reading all the error messages from the resource bundle specified for the application. Custom validators may also be defined.

The validator framework comes as a pluggable set of validation routines that can be applied to form beans (Data beans that capture the user input data). Validator uses two xml files that define the validation routines to be plugged-in and how they need to be applied for the application data.

Validator plug-in:
The validator plug-in needs to be enabled. This is done by specifying the following in the struts-config.xml file (the application’s configuration file).

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

The plug-in loads the xml files specified in the ‘pathnames’ property during initialization.

validator-rules.xml
This file contains all the available preconfigured validations that are available for an application. The routines are java methods that perform specific validations. In most cases the file that comes with the ‘struts’ would suffice. Any other application specific validation routine can to be added to this file if needed.

<form-validation>
   <global>
      <validator name="required"
            classname="org.apache.struts.validator.FieldChecks"
               method="validateRequired"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
                  msg="errors.required"/>
...
  </global>
<form-validation>

Note: The ‘errors.required’ is defined in the resource bundle for the application which takes in one parameter for the name of the field.

validator.xml
This xml file defines the validations that need to be applied to the application’s form beans (the user input data holders). Further it specifies the specific fields that need to be validated and the type of routine that needs to be applied.

<form-validation>
  <formset>
    <form name="UserForm">
      <field property="userFirstName" depends="required">
        <arg0 key="user.firstname"/>
      </field>
      <field property="userLastName"  depends="required">
        <arg0 key="user.lastname"/>
      </field>
    </form>
  </formset>
</form-validation>

Note: The ‘user.firstname’ and ‘user.lastname’ need to be configured in the resource bundle for the application.

The <formset> element is used to separate the validations for each locale if internationalization of validations is required.
The <form name=”XYZ”> attribute is the logical name given to the form bean in the struts-config.xml file for the application.
The <field> attribute ‘property’ corresponds to the field name in the form bean being validated.
Note: Instead of the form bean name the validations can be mapped to the ‘action-mappings’ defined in the struts-config.xml file.

Form Beans
The form beans passing through the validator framework need to extend from the ‘ValidatorForm’ for the validations to be triggered automatically (as against the ActionForm in case struts framework is being used).

import org.apache.struts.validator.ValidatorForm;

public class UserForm extends ValidatorForm {

    private  String userFirstName = null;
    private  String userLastName = null;

        public String getUserFirstName() {
        return userFirstName;
    }
    public void setUserLastName(String userFname) {
        userFirstName = userFname;
    }
...
}

Note: If action-mapping is used in the validator.xml file then the form bean has to extend from “org.apache.struts.validator.ValidatorActionForm” .

JSP
To show the errors on the jsp for the server-side validations the tag <html:errors> needs to be included in the jsp.

Client-side validations
All the above setting enables the validations of the user input data on the server side. To switch on the validations on the client side using javascript the following needs to be added to the jsp pages.

<html>
<head>
   ...
<html:javascript formName="userForm" />
</head>
  ...
...
<html:form action="LoginAction.do" onSubmit="return
                            validateUserForm(this);">

:

:
</html:form>

To force the client side Javascript validation to check all constraints, instead of stopping at the first error, the ‘stopOnFirstError’ property on the Validator PlugIn needs to be set to false.

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

by Rupa Jaganathan