ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

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.