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