Writing Your Own Rules

 < Day Day Up > 



Let's begin with a simple rule for validating a phone number. To create a validation rule, you follow these steps:

  1. Create a Java class.

  2. Add a static method to the Java class that implements the validation routine.

  3. Create an entry in the validator-rules.xml file that associates the static method with a rule.

The first step is to create a Java class. This class does not have to subclass any special class.

Step 2 is to add a static method to the Java class that implements the validation routine. The validation routine gets passed a bean, ValidatorAction, Field, and the servlet request as follows:

 public class CustomValidatorRules {      public static boolean validatePhone(                                Object bean,                                ValidatorAction va,                                Field field,                                ActionErrors errors,                          HttpServletRequest request) { 

The ValidatorAction contains information for dynamically instantiating and running the validation method. The ValidatorAction is the rule. This is the object representation of the XML validator element that we will define in step 3.

The Field contains the list of rules (pluggable validators; for example, ValidatorAction), the associated form property, message arguments, messages, and variables used to perform the validations and generate error messages. This is the object representation of the field element we've been using all along.

Inside the validator method, you need to get the string value of the current field. Then you must see if that String value is a valid phone number. If the field is not a valid phone number, you need to add an error to the ActionErrors as shown in Listing 12.5:

Listing 12.5: Validating a US phone number.

start example
      public static boolean validatePhone(                              Object bean,                              ValidatorAction va,                              Field field,                              ActionErrors errors,                              HttpServletRequest request){               //Get the string value of the current field           String phone = ValidatorUtil.                    getValueAsString(bean, field.getProperty());               //Check to see if the value is a valid phone           char [] chars = phone.toCharArray();           int numberCount=0;           for (int index=0; index < chars.length; index++){                char c = chars[index];                if (Character.isDigit(c)){                     numberCount++;                }else if (Character.isWhitespace(c)){                   //White space okay                } else if (c == '(' || c ==')' || c =='-'){                     // ()- okay too                }                else {                     return false;                }           }                //If not 10 digits then not a valid phone           if (numberCount != 10){                errors.add(field.getKey(),                             Resources.getActionError(request,                               va,                             field));                return false;           } else {                return true;           }      } 
end example

This code checks to see if the string value of the field contains only white space; the characters (,), and -; and digits; for instance, (520) 555-1212, which is the common way to express a phone number in the United States. Then, it checks to see if there were exactly 10 digits, as in 520 555 1212.

Step 3 involves creating an entry in the validator-rules.xml file that associates the static method to a rule. The validator-rules.xml file serves as a deployment descriptor for validation rules. This is the entry you need to add:

 <form-validation>    <global>       <validator name="phone"                  classname="ch12.CustomValidatorRules"                  method="validatePhone"                  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.phone">       </validator>       ... 

The validator element defines the rule. The name attribute specifies the name of the new rule. The classname specifies the name of the new class you just created that contains the static method validatePhone. The method attribute defines the method that will be called. The methodParams specifies the arguments that will be passed to the validatePhone method. Lastly, the msg attribute specifies the resource key of the message that will be used from the resource bundle if a validation failure occurs.

That's it. Now, to actually use the validator rule you need to do the following:

  1. Create a field entry in the inputForm in the validator.xml file that associates the phone property of the inputForm with the new validator rule.

  2. Add the errors.phone message to the resource bundle.

First, add another field attribute that maps this new rule to the phone property of our ActionForm:

     <field property="phone"         depends="required,phone">         <arg0 key="inputForm.phone" />     </field> 

Then add the error message that corresponds to this rule to the application.properties file:

 errors.phone={0} must be a valid phone number. 

What if you wanted to create a more complicated rule—for example, one that you pass a variable to. Let's add the ability to work with 7-digit local phone numbers or 10-digit national phone numbers by using a variable. In order to do this, you need to get the variable by using the field method getVarValue as follows:

      public static boolean validatePhoneExt(                              Object bean,                              ValidatorAction va,                              Field field,                              ActionErrors errors,                              HttpServletRequest request){           String sAllowLocal =                  field.getVarValue("allowLocal");           boolean allowLocal =              sAllowLocal!=null && sAllowLocal.equals("true");           String phone = ValidatorUtil.                  getValueAsString(bean, field.getProperty());           char [] chars = phone.toCharArray();           int numberCount=0;           for (int index=0; index < chars.length; index++){                char c = chars[index];                if (Character.isDigit(c)){                     numberCount++;                }else if (Character.isWhitespace(c)){                   //White space okay                } else if (c == '(' || c ==')' || c =='-'){                     // ()- okay too                }                else {                     return false;                }           }           if (allowLocal == false && numberCount == 10){                return true;           } else if (allowLocal == true &&                     (numberCount == 10 || numberCount==7)){               return true;           }           else{                errors.add(field.getKey(),                         Resources.getActionError(request, va,                         field));             return false;           }      } 

Now that you have defined the variable allowLocal, use it by configuring a variable in the validation.xml file as follows:

             <field property="phone"                           depends="required,phoneext">                    <arg0 key="inputForm.phone" />                   <var>                      <var-name>allowLocal</var-name>                      <var-value>true</var-value>                   </var>             </field> 

start sidebar

Why use strings and not other primitive types? You should use Strings for form property types when you are doing any type of validation with any type of text field. The problem with using other types is that Struts does conversion. Therefore, if you have an integer property, Struts will convert the incoming request parameter into an integer. If the incoming type is invalid, Struts will convert it to a 0, and it is likely that your validation rule will either not run or not run correctly, and the users will just see the field as a 0 instead of the text that they typed in the text field.

end sidebar



 < Day Day Up > 



Professional Jakarta Struts
Professional Jakarta Struts (Programmer to Programmer)
ISBN: 0764544373
EAN: 2147483647
Year: 2003
Pages: 183

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