You are on page 1of 13

Struts javaScript Validation

In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser. Validator Framework emits the JavaScript code which validates the user input on the browser. 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. Enabling the Validator plug- in To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file. <!-- Validator plugin --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEBINF/validation.xml"/> </plug-in> Creating Message Resources Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEBINF\MessageResources.properties file and add the following lines: AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address Developing Validation rules In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml. <!-- Address form Validation--> <form name="AddressForm"> <field property="name"

depends="required"> <arg key="AddressForm.name"/> </field> <field property="address" depends="required"> <arg key="AddressForm.address"/> </field> <field property="emailAddress" depends="required"> <arg key="AddressForm.emailAddress"/> </field> </form> The above definition defines the validation for the form fields name, address and emailAddress. The attribute depends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the <arg key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEBINF\MessageResources.properties). Applying Validation rules to JSP Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows: <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/AddressJavascriptValidation" method="post" onsubmit="return validateAddressForm(this);"> <div align="left"> <p> 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. </p> <p> <html:errors/>

</p> <table> <tr> <td align="center" colspan="2"> <font size="4"><b>Please Enter the Following Details</b></font> </tr> <tr> <td align="right"> <b>Name</b> </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>Address</b> </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>E-mail address</b> </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </div> <!-- Begin Validator Javascript Function--> <html:javascript formName="AddressForm"/>

<!-- End of Validator Javascript Function--> </html:form> </body> </html:html> The code <html:javascript formName="AddressForm"/> is used to plug-in the Validator JavaScript. Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp. <action path="/AddressJavascriptValidation" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/AddressJavascriptValidation.jsp"> <forward name="success" path="/pages/success.jsp"/> </action> Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/AddressJavascriptValidation.jsp">Client Side Validation for Address Form</html:link> <br> The Address Form that validates the data on the client side using Stuts Validator generated JavaScript. </li> Building Example and Testing To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the AddressJavascriptValidation.jsp page. Your browser should show the following out put.

If the fields are left blank and Save button is clicked, browser shows the error message. In this lesson you learned how to use Struts Validator Framework to validate the form on client browser.

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. Its 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 frameworks 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 Validators two configuration files, and creating Form Beans that extend the Validators 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

Create a form bean in your project called CustomerForm and copy following code in it. view source print?
01 package net.viralpatel.struts.validation.form; 02 03 import org.apache.struts.validator.ValidatorForm; 04 05 public class CustomerForm extends ValidatorForm { 06 07 private String name; 08 private String telephone; 09 private String email; 10 private int age; 11 12 public String getName() { 13 return name; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public String getTelephone() { 21 return telephone; 22 } 23 24 public void setTelephone(String telephone) { 25 this.telephone = telephone; 26 } 27 28 public String getEmail() { 29 return email; 30 } 31 32 public void setEmail(String email) { 33 this.email = email; 34 } 35

36 37 38 39 40 41 42 43 }

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. view source print?
1 <!-- Validator Configuration --> 2 <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> 3 <set-property property="pathnames" 4 value="/WEB-INF/validator-rules.xml, 5 /WEB-INF/validation.xml" /> 6 </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 files path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

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

view source print?


01 <?xml version="1.0" encoding="UTF-8" ?> 02 <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules 03 Configuration 1.1.3//EN" "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd 04 "> 05 <form-validation> 06 <global> 07 <constant> 08 <constant-name>telephoneFormat</constant-name> 09 <constant-value>^\d{5,10}$</constant-value> 10 </constant> 11 </global> 12 <formset> 13 <form name="CustomerForm"> 14 <field property="name" depends="required"> 15 <arg key="label.name" /> 16 </field> 17 <field property="age" depends="required, integer, intRange"> 18 <arg0 key="label.age" /> 19 <arg1 key="${var:min}" resource="false"/> 20 <arg2 key="${var:max}" resource="false"/> 21 <var> 22 <var-name>min</var-name> 23 <var-value>1</var-value> 24 </var> 25 <var> 26 <var-name>max</var-name> 27 <var-value>125</var-value> 28 </var> 29 </field> 30 <field property="telephone" depends="required, mask"> 31 <arg key="label.telephone" /> 32 <arg1 key="label.telephone" /> 33 <var> 34 <var-name>mask</var-name> 35 <var-value>${telephoneFormat}</var-value> 36 </var> 37 </field> 38 <field property="email" depends="email"> 39 <arg0 key="label.email" /> 40 <arg1 key="label.email" /> 41 </field> 42 </form> 43 </formset> 44 </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. view source print?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 <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="/Customer.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). view source print?
01 label.name= Name

02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22

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 and copy following content in it. view source print?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 <%@ 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 />

20 <bean:message key="label.email" /> 21 <html:text property="email"></html:text> 22 <br /> 23 <bean:message key="label.telephone" /> 24 <html:text property="telephone"></html:text> 25 <br /> 26 27 <html:submit value="Submit"></html:submit> 28 29 </html:form> 30 </body> 31 </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.

Enter any invalid value in the form and press submit.

You might also like