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   * デフォルトエラーメッセージキー:valid.range
27   * </p>
28   * 
29   * @author agata
30   * @author baba
31   */
32  public class RangeValidator implements ScalarFieldValidator {
33  
34  	/**
35  	 * メッセージヘルパ。
36  	 */
37  	private final MessageHelper messageHelper;
38  
39  	/**
40  	 * 最小値
41  	 */
42  	private final long min;
43  
44  	/**
45  	 * 最大値
46  	 */
47  	private final long max;
48  
49  	/**
50  	 * コンストラクタ
51  	 * 
52  	 * @param min
53  	 *            最小値
54  	 * @param max
55  	 *            最大値
56  	 */
57  	public RangeValidator(final long min, final long max) {
58  		this(min, max, "valid.range");
59  	}
60  
61  	/**
62  	 * エラーメッセージキーを指定するコンストラクタ
63  	 * 
64  	 * @param min
65  	 *            最小値
66  	 * @param max
67  	 *            最大値
68  	 * @param messageKey
69  	 *            エラーメッセージキー
70  	 */
71  	public RangeValidator(final long min, final long max,
72  			final String messageKey) {
73  		this.min = min;
74  		this.max = max;
75  		this.messageHelper = new MessageHelper(messageKey);
76  	}
77  
78  	public void validate(final ValidationContext context, final Object value) {
79  		if (value instanceof String) {
80  			final String str = (String) value;
81  			if (StringUtil.isEmpty(str)) {
82  				return;
83  			}
84  			try {
85  				final long longValue = Long.parseLong(str);
86  				if (longValue >= min && longValue <= max) {
87  					return;
88  				}
89  			} catch (final NumberFormatException e) {
90  			}
91  		} else if (value == null) {
92  			return;
93  		}
94  		context.addMessageInfo(this.messageHelper.createMessageInfo(min, max));
95  	}
96  }