View Javadoc

1   /*
2    * Copyright 2004-2009 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.action.MessageInfo;
19  import org.seasar.cubby.internal.util.StringUtils;
20  import org.seasar.cubby.validator.ScalarFieldValidator;
21  import org.seasar.cubby.validator.ValidationContext;
22  
23  /**
24   * 文字列の最大長を検証します。
25   * <p>
26   * {@link String#length()} メソッドで文字列の長さを求めます。文字列のバイト数でないこと、半角全角も 1
27   * 文字としてカウントされることに注意してください。
28   * </p>
29   * <p>
30   * <table>
31   * <caption>検証エラー時に設定するエラーメッセージ</caption> <tbody>
32   * <tr>
33   * <th scope="row">デフォルトのキー</th>
34   * <td>valid.maxLength</td>
35   * </tr>
36   * <tr>
37   * <th scope="row">置換文字列</th>
38   * <td>
39   * <ol start="0">
40   * <li>フィールド名</li>
41   * <li>このオブジェクトに設定された文字列の最大長</li>
42   * </ol></td>
43   * </tr>
44   * </tbody>
45   * </table>
46   * </p>
47   * 
48   * @author agata
49   * @author baba
50   * @see String#length()
51   */
52  public class MaxLengthValidator implements ScalarFieldValidator {
53  
54  	/**
55  	 * メッセージキー。
56  	 */
57  	private final String messageKey;
58  
59  	/**
60  	 * 最大文字数
61  	 */
62  	private final int max;
63  
64  	/**
65  	 * コンストラクタ
66  	 * 
67  	 * @param max
68  	 *            最大文字数
69  	 */
70  	public MaxLengthValidator(final int max) {
71  		this(max, "valid.maxLength");
72  	}
73  
74  	/**
75  	 * エラーメッセージキーを指定するコンストラクタ
76  	 * 
77  	 * @param max
78  	 *            最大文字数
79  	 * @param messageKey
80  	 *            エラーメッセージキー
81  	 */
82  	public MaxLengthValidator(final int max, final String messageKey) {
83  		this.max = max;
84  		this.messageKey = messageKey;
85  	}
86  
87  	/**
88  	 * {@inheritDoc}
89  	 */
90  	public void validate(final ValidationContext context, final Object value) {
91  		if (value instanceof String) {
92  			final String str = (String) value;
93  			if (StringUtils.isEmpty((String) value)) {
94  				return;
95  			}
96  			if (str.length() <= max) {
97  				return;
98  			}
99  		} else if (value == null) {
100 			return;
101 		}
102 
103 		final MessageInfo messageInfo = new MessageInfo();
104 		messageInfo.setKey(this.messageKey);
105 		messageInfo.setArguments(max);
106 		context.addMessageInfo(messageInfo);
107 	}
108 }