複数フィールドバリデータ
みんな作ってると思うんだけど。
複数項目をまとめてチェックするバリデータ。
早い話が、S2ComparaValidatorの複数版。
targetId="xxx"じゃなくて、targetId="xxx,yyy,zzz"と複数選択できる。
例によって、
- このバリデータを仕掛けた項目が入力されてないと、バリデートされない
- 複数項目の「一番最後の項目」に仕掛けなきゃいけない
辺りには気をつけて。
package examples.jsf.validator; import javax.faces.component.StateHolder; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import org.seasar.framework.exception.EmptyRuntimeException; import org.seasar.jsf.util.ValueHolderUtil; /** * @author cero-t * */ public abstract class S2MultiFieldValidator implements Validator, StateHolder { private String targetId = null; private boolean bTransient = false; public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } public boolean isTransient() { return bTransient; } public void setTransient(boolean transientValue) { this.bTransient = transientValue; } public Object saveState(FacesContext context) { Object values[] = new Object[1]; values[0] = targetId; return values; } public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; targetId = (String) values[0]; } public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (value == null) { return; } UIComponent[] targetComponents = getTargetComponents(component); Object[] targetValues = new Object[targetComponents.length]; for (int i = 0; i < targetComponents.length; i ++) { targetValues[i] = ValueHolderUtil.getValue(targetComponents[i]); } doValidate(context, component, value, targetComponents, targetValues); } protected UIComponent[] getTargetComponents(UIComponent component) { if (targetId == null) { throw new EmptyRuntimeException("targetId"); } String[] targetIds = targetId.split(","); UIComponent[] targetComponents = new UIComponent[targetIds.length]; for (int i = 0; i < targetIds.length; i ++) { targetComponents[i] = component.findComponent(targetIds[i]); if (targetComponents[i] == null) { throw new EmptyRuntimeException(targetIds[i]); } } return targetComponents; } protected abstract void doValidate(FacesContext context, UIComponent component, Object value, UIComponent[] targetComponent, Object targetValues[]) throws ValidatorException; }