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 java.util.regex.Pattern;
20  
21  import org.seasar.cubby.action.MessageInfo;
22  import org.seasar.cubby.internal.util.StringUtils;
23  import org.seasar.cubby.validator.ScalarFieldValidator;
24  import org.seasar.cubby.validator.ValidationContext;
25  
26  /**
27   * 数値であるかを検証します。
28   * <p>
29   * <table>
30   * <caption>検証エラー時に設定するエラーメッセージ</caption> <tbody>
31   * <tr>
32   * <th scope="row">デフォルトのキー</th>
33   * <td>valid.number</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 NumberValidator implements ScalarFieldValidator {
50  
51  	private static final Pattern NUMBER_PATTERN = Pattern
52  			.compile("^[-+]?[0-9]+[.]?[0-9]*$");
53  
54  	/**
55  	 * メッセージキー。
56  	 */
57  	private final String messageKey;
58  
59  	/**
60  	 * コンストラクタ
61  	 */
62  	public NumberValidator() {
63  		this("valid.number");
64  	}
65  
66  	/**
67  	 * エラーメッセージキーを指定するコンストラクタ
68  	 * 
69  	 * @param messageKey
70  	 *            エラーメッセージキー
71  	 */
72  	public NumberValidator(final String messageKey) {
73  		this.messageKey = messageKey;
74  	}
75  
76  	/**
77  	 * {@inheritDoc}
78  	 */
79  	public void validate(final ValidationContext context, final Object value) {
80  		if (value instanceof String) {
81  			final String str = (String) value;
82  			if (StringUtils.isEmpty(str)) {
83  				return;
84  			}
85  			if (NUMBER_PATTERN.matcher(str).find()) {
86  				return;
87  			}
88  		} else if (value == null) {
89  			return;
90  		}
91  
92  		final MessageInfo messageInfo = new MessageInfo();
93  		messageInfo.setKey(this.messageKey);
94  		context.addMessageInfo(messageInfo);
95  	}
96  
97  }