Home > Guides > Programming > Java

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Custom Validators

Last updated Oct 6, 2006.

One of my favorite facets of open source projects is the fact that you have access to source code. Struts publishes their interface and mechanisms to implement validation rules, enabling you to build your own custom validator rules. Validation rules are defined in the validator-rules.xml file, or technically they are in one of the XML files defined in the pathnames property of the Validator plug-in defined in your struts-config.xml file.

In order to develop your own validation rule, you need to do two things:

  1. Create a class (of any type) that creates a static validation method
  2. Add an entry to the validator-rules.xml that defines a reference to that validation method

The method signature for a validation rule is defined as follows:

public static boolean validateSomething(
  Object bean,
  ValidatorAction validatorAction, 
  Field field,
  ActionErrors errors,
  HttpServletRequest request, 
  ServletContext application,
  org.apache.commons.validator.Validator validator,
  java.util.Locale local )

Where the method parameters are defined as follows:

  • bean: bean validation is being performed on
  • validatorAction: the current ValidatorAction being performed
  • field: field object being validated
  • errors: the errors objects to add an ActionError to if the validation fails
  • request: current request object
  • application: the application’s ServletContext
  • validator: the current Validator instance
  • locale: the Locale of the current user

You are not required to define all of these parameters, but your method signature must match the definition you define in validator-rules.xml. As an example consider defining a rule that compares two form fields for equality.

Listing 1. validator-rules.xml addition for "equals" rule

<validator name="equals"
    classname="com.javasrc.struts.validators.StrutsValidator"
    method="validateEquals"
    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"
    depends=""
    msg="errors.equals"/>

Listing 2. validator.xml addition to validate password

<field property="confirmPassword" depends="required,equals">
 <arg0 key="register.confirmPassword"/>
 <var>
  <var-name>otherField</var-name>
  <var-value>password</var-value>
 </var>
</field>

Listing 3. StrutsValidator.java

package com.javasrc.struts.validators;

import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericTypeValidator;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.UrlValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.RequestUtils;

public class StrutsValidator {

public static boolean validateEquals (
  Object bean,
  ValidatorAction validatorAction, 
  Field field,
  ActionErrors errors,
  HttpServletRequest request, 
  ServletContext application) {

  String value = ValidatorUtils.getValueAsString(
    bean, 
    field.getProperty());
  String otherField = field.getVarValue("otherField");
  String otherValue = ValidatorUtils.getValueAsString(
    bean, 
    otherField );

  if (!GenericValidator.isBlankOrNull(value)) {
    try {
     if (!value.equals( otherValue ) ) {
       errors.add(field.getKey(),
        Resources.getActionError(
          application,
          request,
          validatorAction,
          field));

       return false;
     }
    } catch (Exception e) {
       errors.add(field.getKey(),
        Resources.getActionError(
          application,
          request,
          validatorAction,
          field));
       return false;
    }
  }
  return true;
}
}

In this example we use the ValidatorUtils class to extract the value of the current bean's property (in our example confirmPassword.) Next we obtain the property and value of that property for whatever the user defined in the "otherField" variable (in this case the value of the password field.) Finally we compare the two strings for equality by using the equals() method.

Discussions

Read and display the table in the document
Posted Nov 12, 2008 06:01 AM by StrongHead
1 Replies
Correction
Posted Nov 4, 2008 06:09 PM by youssef.mohammed
1 Replies
Instead of synchronising getInstance
Posted Nov 3, 2008 05:42 AM by grahamkelly
1 Replies

Make a New Comment

You must log in in order to post a comment.

Related Resources

Dustin SullivanIf You Are New to Java Programming...
By Dustin SullivanJune 2, 2009 No Comments

We recently sat down with several top Java developers to talk about that state of the language as we approach this year's JavaOne.  As we were wrapping up, we threw one last question at them out of curiosity, and we thought you'd like to see what some of them said.

Steven HainesOracle Buys Sun of $7.4B
By Steven HainesApril 20, 2009 No Comments

In a stunning turn of events, Oracle steps in and buys Sun amist the breakdown of IBM's attempt to acquire Sun.

Steven HainesIBM in talks to buy Sun Microsystems for at least $6.5B
By Steven HainesMarch 18, 2009 No Comments

Reuters reported this morning that IBM is in talks to buy Sun Microsystems, which could "bolster their computer server products against rivals such as Hewlett-Packard Co."

See More Blogs

Informit Network