View Javadoc

1   package org.seasar.cubby.validator.validators;
2   
3   import org.seasar.cubby.validator.ValidationContext;
4   import org.seasar.cubby.validator.Validator;
5   import org.seasar.framework.exception.EmptyRuntimeException;
6   
7   /**
8    * 配列のパラメータに対して入力検証を行います。
9    * @author agata
10   */
11  public class ArrayValidator implements Validator {
12  
13  	private final Validator[] validators;
14  
15  	/**
16  	 * 配列に適用するバリデーション一覧を指定します。
17  	 * @param validators バリデーション
18  	 */
19  	public ArrayValidator(final Validator... validators) {
20  		if (validators == null) {
21  			throw new EmptyRuntimeException("validators");
22  		}
23  		this.validators = validators.clone();
24  	}
25  
26  	public String validate(final ValidationContext ctx) {
27  		final Object value = ctx.getValue();
28  		if (value == null || !value.getClass().isArray()) {
29  			return validateAll(ctx);
30  		}
31  		Object[] values = (Object[])value;
32  		for (Object currentValue : values) {
33  			ValidationContext currentCtx = new ValidationContext(ctx.getName(),
34  					currentValue, ctx.getParams(), ctx.getFormatPattern());
35  			String error = validateAll(currentCtx);
36  			if (error != null) {
37  				return error;
38  			}
39  		}
40  		return null;
41  	}
42  
43  	private String validateAll(final ValidationContext ctx) {
44  		for (Validator v : validators) {
45  			String error = v.validate(ctx);
46  			if (error != null) {
47  				return error;
48  			}
49  		}
50  		return null;
51  	}
52  }