- Java Reference Guide
- Overview
- Table of Contents
- J2SE: Standard Java
- Java Windows NT Services
- Advanced J2SE
- J2SE 1.5.0: "Tiger"
- Java SE 6
- Core Computer Science Principles in Java (Data Structures)
- Annotations
- Java Generics
- Java New I/O
- Java Sound
- Java Applets
- JavaFX
- Java SE Threading
- Resource Management Using Semaphores
- Java Atomic Operations
- JavaTemplate Pages
- Executing Templates with the JtpExecutor
- Java Cryptography Extensions (JCE)
- Java Database Connectivity (JDBC) API
- Jakarta Commons - Net Class Library
- Jakarta Commons HttpClient
- Apache POI
- Regular Expressions
- JavaMail
- Cool Tools
- Building an Really Simple Syndication (RSS) Java App
- Logging with Log4J
- Inside Swing
- Swing Components
- SwingX
- Swing Styled Documents
- Web Rendering in Java Swing Applications
- Java Look-and-Feel Graphics Repository
- Java Media Framework
- Quicktime for Java
- Media in Java Review 2008
- Graphs and Charts
- Holiday Special: Electronic Greeting Card
- Media Framework: Presenter Application
- Standard Widget Toolkit
- JFace
- Java Performance Tuning
- J2EE Performance Tuning
- Caches and Pools
- Java Caching System
- Java Compression and Decompression
- Obfuscating Java Applications
- Continuous Integration
- Load Testing
- Tomcat Clustering
- Enterprise Java Testing
- Automated Unit Testing with JUnit and Ant
- Unit Testing: Tips From The Trenches
- Custom Ant Tasks
- Extensible Markup Language (XML)
- Java Web Technologies
- Web Frameworks
- Performance Analysis Plan
- The Players
- The Evolution of Dynamic Content Generation
- The Model-View-Controller Pattern
- Apache Struts
- Building a Simple Apache Struts Example
- Server-side Form Validation
- Client-side Form Validation
- The Struts Validator
- The Struts Validator – Part II
- Custom Validators
- Tiles
- NetBeans
- Struts Development with MyEclipse
- Struts Development with BEA Workshop for Struts
- Struts Development with BEA Workshop for Struts, Part II
- Summary
- Struts 2
- Wicket New
- JavaServer Faces
- Distributed Programming / RMI
- Servlet Filters
- Building a Robust Java Server
- J2EE: Enterprise Java
- Spring
- Java Design Patterns
- XDoclet
- Hibernate
- Project Backup
- J2EE Project: Hands-On
- Enterprise Java Beans (EJB) 3.0
- Disaster Recovery
- Java Management Extensions (JMX)
- Service-Oriented Architecture
- Web Services
- Project: Building a Web Photo Gallery
- J2ME: Micro Java
- Specialized J2ME
- Optional Packages
- Other Java Technologies
- Derivatives and Competitors
- Java, Engineered for Integration
- Additional Resources
- The World of Java Tools
- Building Java Applications with Ant
- Managing Java Build Lifecycles with Maven
- Source Control with Subversion
- Inversion of Control and Dependency Injection
- Certification
- Roadmap: Becoming an Enterprise Java Developer
- Roadmap: Becoming an Enterprise Java Developer in 2007
- The Business of Enterprise Software
- JavaOne 2006
- JavaOne 2007
- JavaOne 2008 Wrap-Up
- JavaOne 2009 Wrap-Up
- How to Survive in a Turbulent Job Market
- How to Hire the Best Talent
- Cloud Computing
- Enterprise Java in 2008 and Beyond
- Predictions for 2018
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:
- Create a class (of any type) that creates a static validation method
- 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.




Account Sign In
View your cart