Share on Google+Share on Google+

Creating Custom Validators in STRUTS

In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications.

Creating Custom Validators in STRUTS


Author: Murthy Gandikota (

In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

The client-side validation in Struts is well known. Here are some of the available features:

  • required
  • requiredif
  • validwhen
  • minlength
  • maxlength
  • mask
  • byte
  • short
  • integer
  • long
  • float
  • double
  • byteLocale
  • shortLocale
  • integerLocale
  • longLocale
  • floatLocale
  • doubleLocale
  • date
  • intRange
  • longRange
  • floatRange
  • doubleRange
  • creditCard
  • email
  • url

These are found in the validator-rules.xml inside the <validator> tags. The validator-rules.xml file is found in the commons-validator jar.

Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the <global> tag:

    <validator name="matchname"
  function validateName(form) {
  var isValid = true;
  var focusField = null;
  var i = 0;
  var fields = new Array();

  var omatchName= eval('new ' + jcv_retrieveFormName(form) +  '_matchname() ');

  for (var x in omatchName) {
  if (!jcv_verifyArrayElement(x, omatchName[x])) {
  var field = form[omatchName[x][0]];

  if (!jcv_isFieldPresent(field)) {
  fields[i++] = omatchName[x][1];
  } else if (field.value != "administrator") {
  if (fields.length > 0) {
   jcv_handleErrors(fields, focusField);
  return isValid;

To understand the above code:

  • matchname is the new validator we are creating; use can use anything you want (e.g. matchAdmin) remembering that this will be used in another file which will be described later
  • the error message issued in the browser has the key; you can have any name here like errors.admin; once again this will be explained later
  • the Java Script function to call is declared in the method attribute of the validator tag; in the above it is called validateName; you can have any valid Java Script function name (e.g. validateAdmin)
  • the Java Script to process this tag is declared inside CDATA; note that the function name should match EXACTLY with the name declared in the method attribute of the validator tag
  • the field.value != "administrator" is where we actually test the value entered in the browser; you can substitute any string in the place of "administrator"; also you can do more sophisticated checking (e.g. replace all blanks; check for upper/lower case, etc.) if you are an experienced Java Script programmer

To use our matchname validator create a file validation.xml and add the following lines:

<!-- Name form Validation-->
<form name="AdminForm">
  <field  property="name"
   <arg0 key=""/>

Copy the files validation.xml and validator-rules.xml to the directory where your struts-config.xml resides. Let us say it is WEB-INF. Next we have to create the error message for Create a directory WEB-INF/resources and a file in this directory with the name Add the following lines to{0} should be administrator.
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.

Edit struts-configuration.xml and add the following lines

<form-bean name="AdminForm" type="test.AdminForm"/>

   <forward name="success" path="success.jsp"/>

<message-resources parameter="resources/application"/>

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">

Create a JSP file as follows:

<%@ taglib uri="struts-bean.tld" prefix="bean" %>
<%@ taglib uri="struts-html.tld" prefix="html" %>

  <title>Administrator Test</title>
<body bgcolor="white">
<html:form action="/AdminFormValidation" method="post" onsubmit="return validateAdminForm(this);">

<div align="left">
This application shows the use of Struts Validator.<br>
The following form contains fields that are processed by Struts Validator.<br>
Fill in the form and see how JavaScript generated by Validator Framework validates the form.


<td align="right">
<td align="left">
<html:text property="name" size="30" maxlength="30"/>
<td align="right">
<td align="left">

<!-- Begin Validator Javascript Function-->
<html:javascript formName="AddressForm"/>
<!-- End of Validator Javascript Function-->


Then we create the success.jsp

<% out.println("SUCCESS") %>

Then we create the Java Class for the AdminForm

package test;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;

 * Form bean for the Admin Entry Screen.
public class AdminForm extends ActionForm
  private String name=null;
  public void setName(String name){;

  public String getName(){

   * Reset all properties to their default values.
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
  public void reset(ActionMapping mapping, HttpServletRequest request) {;

   * Reset all properties to their default values.
   * @param mapping The mapping used to select this instance
   * @param request The servlet request we are processing
   * @return errors
  public ActionErrors validate(
  ActionMapping mapping, HttpServletRequest request ) {
  ActionErrors errors = new ActionErrors();

  if( getName() == null || getName().length() < 1 ) {
  errors.add("name",new ActionMessage(""));

  return errors;


Create the

package test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AdminAction extends Action
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception{
  return mapping.findForward("success");

Finally compile the classes and restart the web server and view the AdminForm.jsp




Posted on: March 10, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Creating Custom Validators in STRUTS   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image