O'Reilly logo

Jakarta Struts Cookbook by Bill Siggelkow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.7. Validating Field Equality with a Custom Validator

Problem

You want to create a reusable validator in Struts 1.1 that can validate that the value of one field is equal to the value of another.

Solution

Use Matt Raible's TwoFields custom validator. Start by creating a class with a static method that implements the rule, as shown in Example 8-9.

Example 8-9. TwoFields validation rule class

package com.oreilly.strutsckbk.ch08;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;

public class CustomValidatorRules {
    
    public static boolean validateTwoFields( Object bean, 
                                             ValidatorAction va,
                                             Field field,
                                             ActionErrors errors,
                                             HttpServletRequest 
                                             request ) {
        String value = ValidatorUtils.getValueAsString(bean, field.
                       getProperty( ));
        String sProperty2 = field.getVarValue("secondProperty");
        String value2 = ValidatorUtils.getValueAsString(bean, 
                        sProperty2);
        
        if (!GenericValidator.isBlankOrNull(value)) {
            try {
                if (!value.equals(value2)) {
                    errors.add(
                            field.getKey( ),
                            Resources.getActionError(request, va, field));
                    return false;
                }
            } catch (Exception e) {
                errors.add(
                        field.getKey( ),
                        Resources.getActionError(request, va, field));
                return false;
            }
        }

        return true;
    } 
}

Next, add the following validator element, shown ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required