Java
  Home arrow Java arrow Page 2 - Validator
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Validator
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 19
    2005-09-22

    Table of Contents:
  • Validator
  • Validator Overview
  • Included Validations
  • Creating Form Beans
  • Configuring validation.xml
  • Enabling Client-Side Validations
  • Adding a New Validation Rule
  • Internationalizing Validations
  • Create a validation.xml File

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More Java Articles
    More By McGraw-Hill/Osborne


     

    Buy this book now. This article is taken from chapter six of the book The Complete Reference Struts, written by James Holmes (McGraw-Hill/Osborne, 2004; ISBN: 0072231319). Check it out at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT