View Javadoc

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