ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Validator Framework example

Updated on September 27, 2012


Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

The Validator Framework in Struts consist of two XML configuration files. The first one is the validator-rules.xml file which contains the default Struts pluggable validator definitions. You can add new validation rules by adding an entry in this file. The second one is the validation.xml file which contain details regarding the validation routines that are applied to the different Form Beans. These two configuration file should be place somewhere inside the /WEB-INF folder of the application.

Clent Side Address Validation

To accomplish this we have to follow the following steps:

  1. Enabling the Validator plug-in: This makes the Validator available to the system.
  2. Create Message Resources for the displaying the error message to the user.
  3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.
  4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
  5. Build and test: We are required to build the application once the above steps are done before testing. 

Step1:-Make a  web project name viplove and their make a package com.viplove

Step2:-Now a add struts capabilities and after that make a UserForm.Java


 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
package com.viplove.struts.form;

import org.apache.struts.validator.ValidatorForm;

 * MyEclipse Struts
 * Creation date: 04-18-2011
 * XDoclet definition:
 * @struts.form name="userForm"
public class UserForm extends ValidatorForm {
	String username;
	String pwd;
	String pwd2;
	String email;
	public String getUsername() {
		return username;
	public void setUsername(String username) {
		this.username = username;
	public String getPwd() {
		return pwd;
	public void setPwd(String pwd) {
		this.pwd = pwd;
	public String getPwd2() {
		return pwd2;
	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	public String getEmail() {
		return email;
	public void setEmail(String email) { = email;

Now make a action class name as User Action .java

 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
package com.viplove.struts.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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;

import com.yourcompany.struts.form.UserForm;

	public class UserAction extends Action{

		public ActionForward execute(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception {
			UserForm u =(UserForm)form;
			String username = request.getParameter("username");
			String password = request.getParameter("pwd");
			String email = request.getParameter("email");
			String driver = "com.mysql.jdbc.Driver";
			String url = "jdbc:mysql://localhost:3306/viplove";
			Connection connection = DriverManager.getConnection(url,"root","root");
			String ssql="insert into viploveg(username,password,email) values(?,?,?)";
			PreparedStatement pistmt=connection.prepareStatement(ssql);
			int check=0;
			return mapping.findForward("ThanksYou.jsp"); 
			} catch(Exception ex)

			return mapping.findForward("RegisterUser.jsp");

Now we would make the client representation thatis HTML and Jsp Page


<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<b>User Registeration Form</b>

<font color="red">

<html:form action="/Register">

<bean:message key="label.user.username" /> : 
<html:text property="username" size="20"/>
<bean:message key="label.user.pwd" /> : 
<html:text property="pwd" size="20"/>
<bean:message key="label.user.pwd2" /> : 
<html:text property="pwd2" size="20"/>
<bean:message key="" /> : 
<html:text property="email" size="20"/>
<bean:message key="label.user.button.submit" />





<h2>Struts - Validator Example</h2>

Thanks you for the registration



After these Now we would apply validations on the form we need two xml file

1.validation-rules.xml:-These the predefined sets of rule

2.validation.xml :-Inthese we define the validation which is to be performed on our form


<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"

      <form name="userForm">
         <field property="username" depends="required,maxlength,minlength,mask">
         	<msg name="required" key="err.user.username.required" />
			<msg name="maxlength" key="err.user.username.length" />
			<msg name="minlength" key="err.user.username.length" />
			<msg name="mask" key="err.user.username.invalid" />

			<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

			<arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>
         <field property="pwd" depends="required,maxlength,minlength,mask">
         	<msg name="required" key="err.user.pwd.required" />
			<msg name="maxlength" key="err.user.pwd.length" />
			<msg name="minlength" key="err.user.pwd.length" />
			<msg name="mask" key="err.user.pwd.invalid" />

			<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

			<arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>
         <field property="pwd2" depends="validwhen">
         	<msg name="validwhen" key="err.user.pwd2.notmatch" />
					(pwd == *this*)

		 <field property="email" depends="required,email">
		 	<msg name="required" key="" />
		 	<msg name="email" key="" />


Now some validation are to be written in ApplicationResources file


#user module label message = Name
label.user.username = UserName
label.user.pwd = Password
label.user.pwd2 = Confirm Password = Email

label.user.button.submit = Submit

#Error message
err.user.username.required = Username is required.<br/>
err.user.username.length = Username length should be between {0} and {1}.<br/>
err.user.username.invalid = Username is invalid , it should be a-z, A-Z, 0-9, dash "-" or underscore "_".<br/>

err.user.pwd.required = Password is required.<br/>
err.user.pwd.length = Password length should be between {0} and {1}.<br/>
err.user.pwd.invalid = Password is invalid , it should be a-z, A-Z, 0-9.<br/>

err.user.pwd2.notmatch = Confirm password is not match.<br/> = Email is required.<br/> =  Email address is invalid.<br/>

Configure struts.xml

Now we have done validation the thing left is controller design

Controller is strutsconfig.xml to mapp  model and view


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "">

  <data-sources />
  <form-beans >
    <form-bean name="userForm" type="com.yourcompany.struts.form.UserForm" />


  <global-exceptions />
  <global-forwards />
  <action-mappings >
      <forward name="success" path="/ThanksYou.jsp "/>


  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
		<set-property property="pathnames"
		value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>


Now Run Your code and enjoy and dont forget to  comment how it worked........


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)