Home arrow Java arrow Page 2 - Validator
JAVA

Validator


The Struts framework features a built-in database for performing data validations on incoming form data. Its simple interface means that developers can focus on writing validation code; additionally, you can plug your own custom routines into Validator. This article shows you how. It is taken from chapter six of the book The Complete Reference Struts, written by James Holmes (McGraw-Hill/Osborne, 2004; ISBN: 0072231319).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 29
September 22, 2005
TABLE OF CONTENTS:
  1. · Validator
  2. · Validator Overview
  3. · Included Validations
  4. · Creating Form Beans
  5. · Configuring validation.xml
  6. · Enabling Client-Side Validations
  7. · Adding a New Validation Rule
  8. · Internationalizing Validations
  9. · Create a validation.xml File

print this article
SEARCH DEVARTICLES

Validator - Validator Overview
(Page 2 of 9 )

Before getting into the details of using the Validator framework, itís necessary to give an overview of how Validator works. Recall that without Validator, you have to code all of your form data validations into the validate( ) methods of your Form Bean objects. Each Form Bean field that you want to perform a validation on requires you to code logic to do so. Additionally, you have to write code that will store error messages for validations that fail. With Validator, you donít have to write any code in your Form Beans for validations or storing error messages. Instead, your Form Beans extend one of Validatorís ActionForm subclasses that provide this functionality for you.

The Validator framework is set up as a pluggable system of validation routines that can be applied to Form Beans. Each validation routine is simply a Java method that is responsible for performing a specific type of validation and can either pass or fail. By default, Validator comes packaged with several useful validation routines that will satisfy most validation scenarios. However, if you need a validation that is not provided by the framework, you can create your own custom validation routine and plug it into the framework.

Validator uses two XML configuration files to tell it 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 are plugged into the framework and assigns logical names to each of the validations. Additionally, the validator-rules.xml file is used to define client-side JavaScript code for each validation routine. If configured to do so, Validator will emit this JavaScript code to the browser so that validations are performed on the client side as well as the server side. The second configuration file, validation.xml, defines which validation routines are 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 Validator

Using the Validator framework involves enabling the Validator plugin, configuring Validatorís two configuration files, and creating Form Beans that extend Validatorís ActionForm subclasses. The following sections explain how to configure and use the Validator in detail.

Enabling the Validator Plugin

Although the Validator framework comes packaged with Struts, by default Validator is not enabled. In order to enable and use Validator, you have to add to your applicationís struts-config.xml file the following definition for the plug-in tag:

Although the Validator framework comes packaged with Struts, by default Validator is not enabled. In order to enable and use Validator, you have to add to your applicationís file the following definition for the tag:

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

This definition causes Struts to load and initialize the Validator plugin for your application. Upon initialization, the plugin loads the comma-delimited list of Validator configuration files specified by the pathnames property. Each configuration fileís path should be specified using a Web application-relative path, as shown in the preceding example.

Note that your applicationís struts-config.xml file must conform to the Struts Configuration DTD, which specifies the order in which elements are to appear in the file. Because of this, you must place the Validator plug-in tag definition in the proper place in the file. The easiest way to ensure that you are properly ordering elements in the file is to use a tool like Struts Console that automatically formats your configuration file so that it conforms to the DTD.

Configuring validator-rules.xml

The Validator framework is set up as a pluggable system whereby each of its validation routines is simply a Java method that is plugged into the system to perform a specific validation. The validator-rules.xml file is used to declaratively plug in the validation routines that Validator will use for performing validations. Strutsí example applications come packaged with preconfigured copies of this file. Under most circumstances, you will use these preconfigured copies and will not need to modify them unless you are adding your own custom validations to the framework.

The Validator framework is set up as a pluggable system whereby each of its validation routines is simply a Java method that is plugged into the system to perform a specific validation. The file is used to declaratively plug in the validation routines that Validator will use for performing validations. Strutsí example applications come packaged with preconfigured copies of this file. Under most circumstances, you will use these preconfigured copies and will not need to modify them unless you are adding your own custom validations to the framework.

Following is a sample validator-rules.xml file that illustrates how validation routines are plugged into Validator:

<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons 
           Validator Rules Configuration 1.0//EN" 
          "http://jakarta.apache. org/commons/dtds/validator_1_0.dtd">
<form-validation>
  <global>
    <validator name="required"  
       classname="org.apache.struts.validator.FieldChecks"  method="validateRequired"
     
methodParams="java.lang.Object, 
               org.apache.commons.validator.ValidatorAction,
               org.apache.commons.validator.Field,
               org.apache.struts.action.ActionErrors, 
               javax.servlet.http.HttpServletRequest"
           
msg="errors.required">
      <javascript>
        <![CDATA[
       
function validateRequired(form) {
          var isValid = true;
          var focusField = null;
          var i = 0;
          var fields = new Array();
          oRequired = new required();
          for (x in oRequired) {
           
var field = form[oRequired[x][0]];
           
if (field.type == 'text' ||
                field.type == 'textarea' ||
                field.type == 'file' ||
                field.type == 'select-one' ||
                field.type == 'radio' ||
                field.type == 'password') {
              
var value = '';
             
// get field's value
             
if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                 
value = field.options[si].value;
                }
              } else {
                value = field.value;
              }
             
if (trim(value).length == 0) {
                if (i == 0) {
                 
focusField = field;
                }
                fields[i++] = oRequired[x][1];
                isValid = false;
             
}
            }
          }
         
if (fields.length > 0) {
            focusField.focus();
            alert(fields.join('\n'));
         
}
         
return isValid;
        }
       
// Trim whitespace from left and right sides of s.
        function trim(s) {
          return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
        }
       
]]>
      </javascript>
    </validator>
  </global>
</form-validation>

Each validation routine in the validator-rules.xml file has its own definition that is declared with a validator tag. The validator tag is used to assign a logical name to the routine, with the name attribute, and to specify the class and method for the routine. The logical name given to the routine will be used to refer to the routine by other routines in this file as well as by validation definitions in the validation.xml file.

Notice that the validator tag encapsulates a javascript tag. The javascript tag is used to define client-side JavaScript code for performing the same validation on the client side as is performed on the server side.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials