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