Creating Custom Validations

 < Day Day Up > 



Validator comes packaged with several useful validations that will suit most validation scenarios; however, your application may require a specific validation that is not provided by the framework. For this situation, Validator provides a simple interface for creating your own custom validations that can easily be plugged into the framework. Following is a list of the steps you need to take to create your own custom validation:

  1. Create a new validation method.

  2. Add a new validation rule to the validator-rules.xml file.

  3. Add new validation definitions to the validation.xml file.

  4. Add messages to the ApplicationResources.properties file.

The following sections walk through each step of the process in detail, enabling you to create a custom validation based on the Social Security Number validation used in the example Mini HR application in Chapter 2. Remember that the Social Security Number validation in Chapter 2 was defined inside of the SearchForm Form Bean class. Creating a custom validation for social security numbers enables the validation code to be reused and to be used declaratively instead of being hard-coded in each Form Bean that wants to use it.

Creating a Validation Method

The first step in creating a custom validation is to create a validation method that can be called by the Validator framework. Typically, all of an application’s methods for custom validations are grouped into a class of their own, as is the case for the example in this section. However, you can place the method in any class. Your validation method needs to have the following signature:

public static boolean validateSsNum(java.lang.Object,   org.apache.commons.validator.ValidatorAction,   org.apache.commons.validator.Field,   org.apache.struts.action.ActionErrors,   javax.servlet.http.HttpServletRequest); 

Of course, the name of your method will vary, but its arguments should match the types shown in the preceding example. Table 6-2 explains each of the validation method’s arguments.

Table 6-2: The Validation Method Arguments

Argument

Description

java.lang.Object

The Form Bean object (down casted to Object) contains the field to be validated.

org.apache.commons.validator.ValidatorAction

The ValidatorAction object encapsulates the <validator> definition from the validator-rules.xml file for this validation routine.

org.apache.commons.validator.Field

The Field object encapsulates the <field> definition from the validation.xml file for the field that is currently being validated.

org.apache.struts.action.ActionErrors

The ActionErrors object stores validation error messages for the field that is currently being validated.

javax.servlet.http.HttpServletRequest

The HTTPServletRequest object encapsulates the current HTTP request.

Following is the custom validation code for validating social security numbers. Notice that the validateSsNum( ) method conforms to the proper method signature for custom validations.

package com.jamesholmes.minihr; import javax.servlet.http.HttpServletRequest; import org.apache.commons.validator.Field; import org.apache.commons.validator.ValidatorAction; import org.apache.commons.validator.ValidatorUtil; import org.apache.struts.action.ActionErrors; import org.apache.struts.validator.Resources; public class MiniHrValidator {   public static boolean validateSsNum(Object bean,     ValidatorAction action,     Field field,     ActionErrors errors,     HttpServletRequest request)   {     String value =       ValidatorUtil.getValueAsString(bean, field.getProperty());     if (value == null || value.length() < 11) {       errors.add(field.getKey(),         Resources.getActionError(request, action, field));       return false;     }     for (int i = 0; i < 11; i++) {       if (i == 3 || i == 6) {         if (value.charAt(i) != '-') {           errors.add(field.getKey(),             Resources.getActionError(request, action, field));           return false;         }       } else if ("0123456789".indexOf(value.charAt(i)) == -1) {         errors.add(field.getKey(),           Resources.getActionError(request, action, field));         return false;       }     }     return true;   } } 

The validateSsNum( ) method begins by retrieving the value for the field being validated. The value is retrieved by determining the field’s name with a call to field.getProperty( ) and then looking up that field in the Form Bean with a call to ValidatorUtil.getValueAsString( ). The getValueAsString( ) method matches the name of the field with the name of one of the Form Bean fields and then gets that field’s value. The rest of the validateSsNum( ) method performs the actual validation logic. If the validation fails for any reason, an error message will be stored in the errors ActionErrors object.

Adding a New Validation Rule

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



 < Day Day Up > 



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2003
Pages: 134
Authors: James Holmes

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net