View Javadoc

1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.validator.validators;
17  
18  import org.seasar.cubby.validator.MessageHelper;
19  import org.seasar.cubby.validator.ScalarFieldValidator;
20  import org.seasar.cubby.validator.ValidationContext;
21  import org.seasar.framework.util.StringUtil;
22  
23  /**
24   * 文字列の長さの範囲を指定して検証します。
25   * <p>
26   * String#length()メソッドで文字列の長さを求めます。文字列のバイト数でないこと、半角全角も1文字としてカウントされることに注意してください。
27   * </p>
28   * <p>
29   * デフォルトエラーメッセージキー:valid.rangeLength
30   * </p>
31   * 
32   * @author agata
33   * @author baba
34   */
35  public class RangeLengthValidator implements ScalarFieldValidator {
36  
37  	/**
38  	 * メッセージヘルパ。
39  	 */
40  	private final MessageHelper messageHelper;
41  
42  	/**
43  	 * 最小文字数
44  	 */
45  	private final int min;
46  
47  	/**
48  	 * 最大文字数
49  	 */
50  	private final int max;
51  
52  	/**
53  	 * コンストラクタ
54  	 * 
55  	 * @param min
56  	 *            最小文字数
57  	 * @param max
58  	 *            最大文字数
59  	 */
60  	public RangeLengthValidator(final int min, final int max) {
61  		this(min, max, "valid.rangeLength");
62  	}
63  
64  	/**
65  	 * エラーメッセージキーを指定するコンストラクタ
66  	 * 
67  	 * @param min
68  	 *            最小文字数
69  	 * @param max
70  	 *            最大文字数
71  	 * @param messageKey
72  	 *            エラーメッセージキー
73  	 */
74  	public RangeLengthValidator(final int min, final int max,
75  			final String messageKey) {
76  		this.min = min;
77  		this.max = max;
78  		this.messageHelper = new MessageHelper(messageKey);
79  	}
80  
81  	public void validate(final ValidationContext context, final Object value) {
82  		if (value instanceof String) {
83  			final String str = (String) value;
84  			if (StringUtil.isEmpty(str)) {
85  				return;
86  			}
87  
88  			final int length = str.length();
89  			if (length >= min && length <= max) {
90  				return;
91  			}
92  		} else if (value == null) {
93  			return;
94  		}
95  		context.addMessageInfo(this.messageHelper.createMessageInfo(min, max));
96  	}
97  
98  }