Validation is an important part of many web applications. Input can be validated on the client side or the server side. The Validator framework can be used to simplify input validations on both sides. This tutorial explains how.
Validators: Introducing Struts Validator Framework - Validator Framework- A Real world Example (Page 3 of 4 )
The login form is present in all web-based applications. I will be using the validations required on the user name and password fields. This login form is a part of an email client I am currently developing. To configure an application to use the Validator framework, you must take the following steps.
Configure the Application
To configure the application, the XML files need to be placed where the class loader would be able to access them. Though they can be placed anywhere theoretically, it is always better to place them directly inside the WEB-INF directory of the application. In my application, they are kept directly under the WEB-INF directory. Since all the versions since Struts version 1.1 contain the Validator framework as their integral part, there is no requirement to separately download them.
Configure the validations.xml file
The downloadable Struts archive contains the two XML files I am using as my templates. The Validator-rules.xml doesn’t require any modification. But the validations.xml requires some modification. So let's get started.
The root element of validations.xml is <form-validation> tag.
<form validation> : : </ form-validation>
Next comes the tag representing the collection of form beans -- the <formset> tag. It encapsulates all the form beans present in an application.
Then the <form> tag comes. This tag corresponds to each form bean. That means if there are ten form beans in an application there will be ten <form> tags with the name attribute corresponding to the names of the form beans. The name of the form bean related to the login page(Login.jsp) is “loginFormBean,” so the value of the name attribute of the <form> tag is “loginFormBean.”
The fields that have to be validated are provided as a property attribute of the <field> tag. This tag contains one more property that is used to specify the validations to be performed on the field -- the depends property. If there is more than one validation, they can be separated by a comma. Here only mandatory field validation is needed. Hence the “depends” attribute contains the value “required.”
Next is the message resource to be used to show the error message when validation fails. This is done by using the <arg0> tag. The key attribute is used to specify the key of the resource bundle related to the message to be used.