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