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 ...
Get Jakarta Struts Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.