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   * 検証対象が null の場合に検証エラーとなります。対象が文字列の場合はの長さが 0 の場合にも検証エラーとなります。
28   * </p>
29   * <p>
30   * <table>
31   * <caption>検証エラー時に設定するエラーメッセージ</caption> <tbody>
32   * <tr>
33   * <th scope="row">デフォルトのキー</th>
34   * <td>valid.required</td>
35   * </tr>
36   * <tr>
37   * <th scope="row">置換文字列</th>
38   * <td>
39   * <ol start="0">
40   * <li>フィールド名</li>
41   * </ol></td>
42   * </tr>
43   * </tbody>
44   * </table>
45   * </p>
46   * 
47   * @author agata
48   * @author baba
49   */
50  public class RequiredValidator implements ScalarFieldValidator {
51  
52  	/**
53  	 * メッセージキー。
54  	 */
55  	private final String messageKey;
56  
57  	/**
58  	 * コンストラクタ
59  	 */
60  	public RequiredValidator() {
61  		this("valid.required");
62  	}
63  
64  	/**
65  	 * エラーメッセージキーを指定するコンストラクタ
66  	 * 
67  	 * @param messageKey
68  	 *            エラーメッセージキー
69  	 */
70  	public RequiredValidator(final String messageKey) {
71  		this.messageKey = messageKey;
72  	}
73  
74  	/**
75  	 * {@inheritDoc}
76  	 */
77  	public void validate(final ValidationContext context, final Object value) {
78  		if (value instanceof String) {
79  			final String str = (String) value;
80  			if (!StringUtils.isEmpty(str)) {
81  				return;
82  			}
83  		} else if (value != null) {
84  			return;
85  		}
86  
87  		final MessageInfo messageInfo = new MessageInfo();
88  		messageInfo.setKey(this.messageKey);
89  		context.addMessageInfo(messageInfo);
90  	}
91  
92  }