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