Java
  Home arrow Java arrow Page 7 - 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  
Moblin 
JMSL Numerical Library 
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 - Adding a New Validation Rule


    (Page 7 of 9 )

    After the custom validation code has been created, a new validation rule needs to be added to the validator-rules.xml file. As discussed earlier in this chapter, validation rules “plug” validation methods into the Validator. Once defined in validator-rules.xml, as shown here, the validation rule can be referenced in the validation.xml file:

    <validator name="ssNum" 
          classname="com.jamesholmes.minihr.MiniHrValidator"
            method="validateSsNum"
     
    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.ssNum">
      <javascript>
        <![CDATA[
       
    function validateSsNum(form) {
          var bValid = true;
          var focusField = null;
          var i = 0;
          var fields = new Array();
          oSsNum = new ssNum();
         
    for (x in oSsNum) {
            if ((form[oSsNum[x][0]].type == 'text' ||
                 form[oSsNum[x][0]].type == 'textarea') &&
                (form[oSsNum[x][0]].value.length > 0))
           
    {
              var value = form[oSsNum[x][0]].value;
              var bRightFormat = true;
             
    if (value.length != 11) {
                bRightFormat = false;
              }
             
    for (var n = 0; n < 11; n++) {
                if (n == 3 || n == 6) {
                  if (value.substring(n, n+1) != '-') {
                   bRightFormat = false;
                  }
                } else if ("0123456789".indexOf(
                             value.substring(n, n+1)) == -1) {
                    bRightFormat = false;
                }
              }
             
    if (!bRightFormat) {
                if (i == 0) {
                
    focusField = form[oSsNum[x][0]];
                }
                fields[i++] = oSsNum[x][1];
                bValid = false;
             
    }
           
    }
          }
          if (fields.length > 0) {
            
    focusField.focus();
            
    alert(fields.join('\n'));
          }
          return bValid;
       
    }
        ]]>
      </javascript>
    </validator>

    As you can see, the validation rule applies a name to the validation with the name attribute; specifies the class that the validation method is housed in with the classname attribute; and specifies the validation method’s arguments with the methodParams attribute. The msg attribute specifies a key that will be used to look up an error message in the ApplicationResources.properties file if the validation fails. Note that the name applied with the name attribute is the logical name for the rule and will be used to apply the rule to definitions in the validation.xml file.

    The preceding custom validation rule also defines JavaScript code, inside the opening and closing <javascript> elements, which will be used if client-side validation is enabled when using the rule. The JavaScript code simply performs the same validation on the client side as is performed on the server side. If the JavaScript validation fails, it will alert the user and prevent the HTML form from being submitted.

    Note that validation rules must be placed underneath the <global> element in the validator-rules.xml file, as shown here:

    <form-validation>
     
    <global>
       
    <validator name="ssnum" …/>
       

       

     
    </global>
    </form-validation>

    Of course, the order of the <validator> elements underneath the <global> element is arbitrary, so you can place the new “ssnum” validation rule anywhere.

    Adding New Validation Definitions

    Once you have defined your custom validation rule in the validator-rules.xml file, you can make use of it by referencing its logical name in the validation.xml file:

    <!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>
      <formset>
        <form name="searchForm">
          <field property="ssNum" depends="required,ssNum"> 
            <arg0 key="prompt.ssNum"/>
          </field>
        </form>
      </formset>
    </form-validation>

    In the preceding validation definition, each of the comma-delimited values of the field tag’s depends attribute corresponds to the logical name of a validation rule defined in the validation-rules.xml file. The use of “ssNum” instructs Validator to use the custom Social Security Number validation. Each time you want to use the new Social Security Number validation, you simply have to add its logical name to the depends attribute of a field tag.

    Adding Messages to the ApplicationResources.properties File

    The final step in creating a custom validation is to add messages to the ApplicationResources.properties file:

    prompt.ssNum=Social Security Number
    errors.ssNum={0} is not a valid Social Security Number

    Remember that the errors.ssNum message key was specified by the msg attribute of the validator tag for the custom validation rule in the validator-rules.xml file. The key’s corresponding message will be used if the validation fails. The prompt.ssNum message key was specified by the arg0 tag of the validation definition in the validation.xml file. Its corresponding message will be used as the parametric replacement for the errors.ssNum message’s {0} parameter. Thus, if the Social Security Number custom validation fails, the following error message will be generated by substituting the prompt.ssNum message for {0} in the errors.ssNum message:

    Social Security Number is not a valid Social Security Number

    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