Home arrow Java arrow Page 7 - 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 - 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


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