Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

8.9. Validating Two or More Choices

Problem

You need to check that two or more choices have been picked from a set of checkboxes or a list of options.

Solution

Use my minchoices pluggable Validator rule. The rule implementation is shown in Example 8-13.

Example 8-13. Validating minimum choices

package com.oreilly.strutsckbk.ch08; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.validator.Field; import org.apache.commons.validator.ValidatorAction; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.Resources; public class ValidatorRules { public static boolean validateMinChoices(Object bean, ValidatorAction va, Field field, ActionMessages errors, HttpServletRequest request) { try { Object values = PropertyUtils.getProperty(bean, field. getProperty( )); int minChoices = Integer.parseInt(field.getVarValue ("minChoices")); if (!(values == null)) { int numChoices = 0; if (values instanceof Object[]) { numChoices = ((Object[])values).length; } else if (values instanceof Collection) { numChoices = ((Collection) values).size( ); } else { errors.add(field.getKey( ), Resources.getActionMessage(request, va, field)); return false; } if (numChoices < minChoices) { errors.add(field.getKey( ), Resources.getActionMessage(request, va, field)); return false; } } } catch (Exception e) { errors.add(field.getKey( ), Resources.getActionMessage(request, va, field)); return ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page