View Javadoc

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