1 /*
2 * Copyright 2004-2010 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
17 package org.seasar.cubby.validator.validators;
18
19 import org.seasar.cubby.action.MessageInfo;
20 import org.seasar.cubby.internal.util.StringUtils;
21 import org.seasar.cubby.validator.ScalarFieldValidator;
22 import org.seasar.cubby.validator.ValidationContext;
23
24 /**
25 * 数値の範囲を検証します。
26 * <p>
27 * <table>
28 * <caption>検証エラー時に設定するエラーメッセージ</caption> <tbody>
29 * <tr>
30 * <th scope="row">デフォルトのキー</th>
31 * <td>valid.range</td>
32 * </tr>
33 * <tr>
34 * <th scope="row">置換文字列</th>
35 * <td>
36 * <ol start="0">
37 * <li>フィールド名</li>
38 * <li>このオブジェクトに設定された数値の最小値</li>
39 * <li>このオブジェクトに設定された数値の最大値</li>
40 * </ol></td>
41 * </tr>
42 * </tbody>
43 * </table>
44 * </p>
45 *
46 * @author agata
47 * @author baba
48 */
49 public class RangeValidator implements ScalarFieldValidator {
50
51 /**
52 * メッセージキー。
53 */
54 private final String messageKey;
55
56 /**
57 * 最小値
58 */
59 private final long min;
60
61 /**
62 * 最大値
63 */
64 private final long max;
65
66 /**
67 * コンストラクタ
68 *
69 * @param min
70 * 最小値
71 * @param max
72 * 最大値
73 */
74 public RangeValidator(final long min, final long max) {
75 this(min, max, "valid.range");
76 }
77
78 /**
79 * エラーメッセージキーを指定するコンストラクタ
80 *
81 * @param min
82 * 最小値
83 * @param max
84 * 最大値
85 * @param messageKey
86 * エラーメッセージキー
87 */
88 public RangeValidator(final long min, final long max,
89 final String messageKey) {
90 this.min = min;
91 this.max = max;
92 this.messageKey = messageKey;
93 }
94
95 /**
96 * {@inheritDoc}
97 */
98 public void validate(final ValidationContext context, final Object value) {
99 if (value instanceof String) {
100 final String str = (String) value;
101 if (StringUtils.isEmpty(str)) {
102 return;
103 }
104 try {
105 final long longValue = Long.parseLong(str);
106 if (longValue >= min && longValue <= max) {
107 return;
108 }
109 } catch (final NumberFormatException e) {
110 }
111 } else if (value == null) {
112 return;
113 }
114
115 final MessageInfo messageInfo = new MessageInfo();
116 messageInfo.setKey(this.messageKey);
117 messageInfo.setArguments(min, max);
118 context.addMessageInfo(messageInfo);
119 }
120 }