Struts Validation Framework Tutorial with example.

apache struts logo
Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

package net.viralpatel.struts.validation.form;

import org.apache.struts.validator.ValidatorForm;

public class CustomerForm extends ValidatorForm {

	private String name;
	private String telephone;
	private String email;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

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

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
	<constant>
	<constant-name>telephoneFormat</constant-name>
	<constant-value>^\d{5,10}$</constant-value>
	</constant>
</global>
<formset>
	<form name="CustomerForm">
		<field property="name" depends="required">
			<arg key="label.name" />
		</field>
		<field property="age" depends="required, integer, intRange">
			<arg0 key="label.age" />
			<arg1 key="${var:min}" resource="false"/>
			<arg2 key="${var:max}" resource="false"/>
			<var>
				<var-name>min</var-name>
				<var-value>1</var-value>
			</var>
			<var>
				<var-name>max</var-name>
				<var-value>125</var-value>
			</var>
		</field>
		<field property="telephone" depends="required, mask">
			<arg key="label.telephone" />
			<arg1 key="label.telephone" />
			<var>
				<var-name>mask</var-name>
				<var-value>${telephoneFormat}</var-value>
			</var>
		</field>
		<field property="email" depends="email">
			<arg0 key="label.email" />
			<arg1 key="label.email" />
		</field>
	</form>
</formset>
</form-validation>

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. <field> tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

<form-beans>
	<form-bean name="CustomerForm"
		type="net.viralpatel.struts.validation.form.CustomerForm" />
</form-beans>
...
...
...
<action-mappings>
...
	<action path="/customer" name="CustomerForm" validate="true"
		input="/index.jsp"
		type="net.viralpatel.struts.validation.action.CustomerAction">
		<forward name="success" path="/Customer.jsp" />
		<forward name="failure" path="/index.jsp" />
	</action>
...
</action-mappings>

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).

label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age

# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL></font>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>Struts Validation Framework example.</title>
</head>
<body>

<html:errors />
<html:javascript formName="CustomerForm" />

<html:form action="/customer">

	<bean:message key="label.name" />
	<html:text property="name"></html:text>
	<br />
	<bean:message key="label.age" />
	<html:text property="age"></html:text>
	<br />
	<bean:message key="label.email" />
	<html:text property="email"></html:text>
	<br />
	<bean:message key="label.telephone" />
	<html:text property="telephone"></html:text>
	<br />

	<html:submit value="Submit"></html:submit>

</html:form>
</body>
</html>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.

struts-validator-form-screen2

Post your comments / doubts on this tutorial.



78 Comments

  • krishna wrote on 31 July, 2010, 19:35

    I want to know the flow of this example. I tried this i m not getting the output. so please help me.

  • Shyam wrote on 20 August, 2010, 4:46

    when i submit all bean property goes to success.jsp but the validation part is not working.
    plug in rules& validation.xml are added.

    eclipse & tomcat6.0 i am using.
    errors on console after submit —->

    ug 19, 2010 4:42:49 PM org.apache.struts.validator.ValidatorForm validate
    SEVERE: org.apache.struts.validator.FieldChecks.validateRequired(java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest)
    org.apache.commons.validator.ValidatorException: org.apache.struts.validator.FieldChecks.validateRequired(java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest)
    at org.apache.commons.validator.ValidatorAction.loadValidationMethod(ValidatorAction.java:627)
    at org.apache.commons.validator.ValidatorAction.executeValidationMethod(ValidatorAction.java:557)
    at org.apache.commons.validator.Field.validateForRule(Field.java:827)
    at org.apache.commons.validator.Field.validate(Field.java:906)
    at org.apache.commons.validator.Form.validate(Form.java:174)
    at org.apache.commons.validator.Validator.validate(Validator.java:367)
    at org.apache.struts.validator.ValidatorForm.validate(ValidatorForm.java:110)
    at org.apache.struts.action.RequestProcessor.processValidate(RequestProcessor.java:950)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:207)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Unknown Source)

  • Shyam wrote on 20 August, 2010, 5:29

    Viral its a diff. problem — when i am connected to the NET the code works fine …. i have given the URI of jsp html & bean tld of ” WEB-INF ” so what should i do to work at a stand alone system.

    pls help. Thank in advance.

  • Suhasini wrote on 14 September, 2010, 16:31

    Hi Viral,

    Can you please tell me where to put properties file in our application..
    Thanx in advance..

    • manju wrote on 7 October, 2011, 11:16

      hi suhasini,,,,make a source folder on Java Resources and create a new file with the name applicationresources.properties in it,,,,,thats it.

  • Chandra Sekhar wrote on 24 September, 2010, 16:50

    Hi friends
    I have executed above login application. These are the errors I got.
    exception

    org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: ValidatorResources not found in application scope under key “org.apache.commons.validator.VALIDATOR_RESOURCES”
    root cause
    javax.servlet.ServletException: javax.servlet.jsp.JspException: ValidatorResources not found in application scope under key “org.apache.commons.validator.VALIDATOR_RESOURCES”
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:850)
    root cause
    javax.servlet.jsp.JspException: ValidatorResources not found in application scope under key “org.apache.commons.validator.VALIDATOR_RESOURCES”
    org.apache.struts.taglib.html.JavascriptValidatorTag.renderJavascript(JavascriptValidatorTag.java:373)
    Could u plz help me to solve these errors…….
    Thankz in advance.

  • atul wrote on 26 October, 2010, 13:55

    thanks

  • SANDHYARAJ SWARGAM wrote on 29 November, 2010, 11:34

    hello sir,
    this example is very good, but u explain different validations,

  • Akshay wrote on 15 December, 2010, 16:25

    I am getting Error :– Exception creating bean of class CustomerForm.
    Please help

  • Abhishek wrote on 16 December, 2010, 15:18

    When I ran this program I got an error mentioning….java.lang.NullPointerException: Depends string “required” was not found in validator-rules.xml.
    please tell me what I need do now?

  • tskarthikeyan wrote on 4 February, 2011, 0:00

    I’ve tried to execute this Struts validator example:

    But when running on server, its giving the below error:

    Feb 4, 2011 12:23:15 AM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Feb 4, 2011 12:23:16 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:StrutsValidationExample’ did not find a matching property.
    Feb 4, 2011 12:23:16 AM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8000
    Feb 4, 2011 12:23:16 AM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 942 ms
    java.lang.NoClassDefFoundError: org/apache/commons/validator/ValidatorResourcesInitializer
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.validator.ValidatorResourcesInitializer
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    … 22 more
    Feb 4, 2011 12:23:22 AM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /StrutsValidationExample threw load() exception
    java.lang.ClassNotFoundException: org.apache.commons.validator.ValidatorResourcesInitializer
    at org.apache.struts.validator.ValidatorPlugIn.initResources(ValidatorPlugIn.java:224)
    SEVERE: Servlet.service() for servlet jsp threw exception
    java.lang.NoSuchMethodError: org.apache.commons.validator.ValidatorResources.get(Ljava/util/Locale;Ljava/lang/Object;)Lorg/apache/commons/validator/Form;
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)

  • sid wrote on 22 February, 2011, 8:58

    Please provide Your example code for download . so that Fresher can understand easily

  • Rahul wrote on 23 March, 2011, 21:08

    I m getting the below error.Plz help me
    SEVERE: Servlet.service() for servlet jsp threw exception
    javax.servlet.jsp.JspException: ValidatorResources not found in application scope under key “org.apache.commons.validator.VALIDATOR_RESOURCES”
    at org.apache.struts.taglib.html.JavascriptValidatorTag.renderJavascript(JavascriptValidatorTag.java:373)
    at java.lang.Thread.run(Thread.java:619)

  • Azinyue wrote on 5 May, 2011, 23:14

    I also getting the ValidatorResources not found – error, and nothing I have done so far seems to make this go away.
    I am using a struts 1.2 with commons-validator-1.3.1.jar hope this doesn’t mess things up for me. Pls help if possible.

  • Baskar wrote on 15 June, 2011, 20:24

    Thanks… Good Explanation.. But I would like to know the meaning of this line. “<html:javascript formName="CustomerForm" " . That is Any javascript is written or it will taken from xml file?

  • pitchaiah wrote on 23 June, 2011, 7:48

    i am working the struts validation for login page. I am not able to test the password consecutive.
    can you please help me how to test password consecutive.

    Like:- Admin123 is correct password
    AAdmin123 in not correct

    Regards,
    Pitch

  • sujit wrote on 18 July, 2011, 16:58

    Hello!!
    I tried to excute the thing, but the things are not working. One thing i want to ask is that ypu ahve mentioned about the validation-rules.xml. But you ahve not given any code for this xml file. SO can you plaes brief me about this validation-rules.xml . Thanks in advance.

  • avantika wrote on 4 August, 2011, 19:48

    i m getting http:status404 exception that the application cannot receive the Servlet action .
    kindly help me .
    Thanks in advance.

  • satya wrote on 20 September, 2011, 10:32

    Hi Sir,
    This example is good & easy to understand.
    But, where is the CustomerAction.java file?
    How to write that? Which logic has to implement in that?

    Thanks & Regards,
    Satya.

  • abhimeet wrote on 2 February, 2012, 1:26

    i m getting the following error.. reply fast.

    A form must be defined in the Commons Validator configuration when dynamicJavascript=”true” is set.

  • abhimeet wrote on 2 February, 2012, 1:28

    also i want to show the error msgs in an alert box.

  • lalitha wrote on 20 March, 2012, 17:12

    Hi,
    I am new to struts.. Can you please provide the CustomerAction class and customer.jsp files..

  • Jonnathan Q wrote on 6 April, 2012, 22:34

    Hi,

    I was wondering about this line “”, you put it into the code but you are not using it at all. By other hand, javascript code should be included into tags, i say “should” and not “must” because is not really mandatory but including javascript this way is just a matter of order. Back to the topic, that javascript line allows you to do the validation before the data is send to the server, so this saves you time and bandwidth, to use it you must add an event to your form, on the sample jsp code just put the form line like this: , so now instead of get some messages on the page body the messages will appear in a pop-up warning window

Leave a Reply

Your email address will not be published. Required fields are marked *

*