The Struts validator framework provides many generic validation methods to make the validation work more easily and maintainability. With Struts validator, you need to declared the validation function into a xml file instead of the ActionForm validate() method, it can make the Struts validation more standardization, reusable and less duplicated codes.

Download this example – Struts-Validator-Example.zip

Using Struts Validator framework

Here’s the quick guide to use the Struts Validator framework.

1. Validator PlugIn

To use the Struts validator plugin, you need to include the “ValidatorPlugIn” class into the struts-config.xml file.

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

The “validator-rules.xml” file contains all the generic validator name, you can get this file in the Struts distribution library, (Do not create this file yourself). And the “validator-user.xml” contains all your form field validation.

2. Validator Form

For form bean need to use the validator framework, it have to extends the ValidatorForm, not ActionForm.

import org.apache.struts.validator.ValidatorForm;
 
public class UserForm extends ValidatorForm{
..

3. validator-user.xml

An userForm bean, email property, and attach the “required” and “email” validator to the email property. The “required” validator will make sure the filed is not blank, and “email” validator is used to check the correct email format. Both “required” and “email” validators are declared in “validator-rules.xml” file.

<form-validation>
   <formset>
      <form name="userForm">
 
		 <field property="email" depends="required,email">
 
		 	<msg name="required" key="err.user.email.required" />
		 	<msg name="email" key="err.user.email.invalid" />
 
		 </field>
 
     </form>
  </formset>
</form-validation>

Struts Validator Framework Example

The best way to understand about the Struts validator framework is create a simple application and walk through the validation works. Here’s a simple user registration form to use the Struts validator framework to check the username, password and email.

1. Action

Action class , just forward a success request.

UserAction.java

package com.mkyong.user.action;
 
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 UserAction extends Action{
 
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
	throws Exception {
 
		return mapping.findForward("success");
	}
}

2. UserForm

UserForm extends the ValidatorForm class.

UserForm.java

package com.mkyong.user.form;
 
import org.apache.struts.validator.ValidatorForm;
 
public class UserForm extends ValidatorForm{
 
	String username;
	String pwd;
	String pwd2;
	String email;
 
	//getter and setter methods
 
}

3. Properties file

A properties file contains all the label and error messages.

user.properties

#user module label message
label.user.name = Name
label.user.username = UserName
label.user.pwd = Password
label.user.pwd2 = Confirm Password
label.user.email = 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/>
 
err.user.email.required = Email is required.<br/>
err.user.email.invalid =  Email address is invalid.<br/>

4. View Page

A simple jsp page to create all require the text field, and a simple thank you page

RegisterUser.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
</head>
<body>
 
<h2>Struts - Validator Example</h2>
 
RegisterUser.jsp
<b>User Registeration Form</b>
<br/><br/>
 
<font color="red">
<html:errors/>
</font>
 
<html:form action="/Register">
 
<br/>
<bean:message key="label.user.username" /> : 
<html:text property="username" size="20"/>
<br/>
<bean:message key="label.user.pwd" /> : 
<html:text property="pwd" size="20"/>
<br/>
<bean:message key="label.user.pwd2" /> : 
<html:text property="pwd2" size="20"/>
<br/>
<bean:message key="label.user.email" /> : 
<html:text property="email" size="20"/>
<br/><br/>
<html:submit>
<bean:message key="label.user.button.submit" />
</html:submit>
 
</html:form>
 
</body>
</html>

ThanksYou.jsp

<html>
<head>
</head>
<body>
 
<h2>Struts - Validator Example</h2>
 
Thanks you for the registration
 
</body>
</html>

5. Struts configuration

Configure action , form mappings and register the “ValidatorPlugIn” plug in.

struts-connfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
 
<struts-config>
 
   <form-beans>
	<form-bean name="userForm" type="com.mkyong.user.form.UserForm" />	
   </form-beans>
 
   <action-mappings>
 
	 	<action
			path="/Register"
			type="com.mkyong.user.action.UserAction"
			name="userForm"
			input="/pages/RegisterUser.jsp"
			>
 
			<forward name="success" path="/pages/ThanksYou.jsp"/>
 
		</action>
 
		<action
			path="/RegisterUserPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/RegisterUser.jsp"/>
 
   </action-mappings>
 
   <message-resources
		parameter="com.mkyong.user.properties.user" />
 
   <plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
	<set-property property="pathnames"
	value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>
 
   </plug-in>
 
</struts-config>

6. validator-user.xml

Define the validator for the userForm’s username, password and email property.

validator-user.xml

<!DOCTYPE form-validation PUBLIC
 "-//Apache Software Foundation
//DTD Commons Validator Rules Configuration 1.3.0//EN"
 "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">
 
<form-validation>
   <formset>
      <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"/>
 
                <var>
            	        <var-name>minlength</var-name>
		        <var-value>3</var-value>
		</var>		
		<var>
			<var-name>maxlength</var-name>
			<var-value>15</var-value>
		</var>
                <var>
			<var-name>mask</var-name>
			<var-value>^[a-zA-Z0-9-_]*$</var-value>
		</var>
         </field>
 
         <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"/>
 
                <var>
            	        <var-name>minlength</var-name>
			<var-value>7</var-value>
		</var>		
		<var>
			<var-name>maxlength</var-name>
			<var-value>15</var-value>
		</var>
                <var>
			<var-name>mask</var-name>
			<var-value>^[a-zA-Z0-9]*$</var-value>
		</var>
         </field>
 
         <field property="pwd2" depends="validwhen">
 
         	<msg name="validwhen" key="err.user.pwd2.notmatch" />
 
		<var>
			<var-name>test</var-name>
			<var-value>
				(pwd == *this*)
			</var-value>
		</var>
	 </field>
 
	<field property="email" depends="required,email">	 
	 	<msg name="required" key="err.user.email.required" />
	 	<msg name="email" key="err.user.email.invalid" />
	 </field>
 
     </form>
  </formset>
</form-validation>

7. Demo

http://localhost:8080/StrutsExample/RegisterUserPage.do

Struts-Validator-Example-1

http://localhost:8080/StrutsExample/Register.do

Struts-Validator-Example-2

The validation codes are descriptive enough to know how it work, if you want to know details, and also other available validators , please check the reference website below.

Reference

Struts validator documentation – http://struts.apache.org/1.2.4/userGuide/dev_validator.html

Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at Struts 1.x Tutorials