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 java.math.BigDecimal;
19  
20  import org.seasar.cubby.validator.MessageHelper;
21  import org.seasar.cubby.validator.ScalarFieldValidator;
22  import org.seasar.cubby.validator.ValidationContext;
23  import org.seasar.framework.util.StringUtil;
24  
25  /**
26   * 数値かどうかを検証します。
27   * <p>
28   * 数値かどうかの検証は {@link BigDecimal#BigDecimal(String)} で行っています。
29   * <p>
30   * デフォルトエラーメッセージキー:valid.number
31   * </p>
32   * 
33   * @author agata
34   * @author baba
35   * @see BigDecimal#BigDecimal(String)
36   * @since 1.0.0
37   */
38  public class NumberValidator implements ScalarFieldValidator {
39  
40  	/**
41  	 * メッセージヘルパ。
42  	 */
43  	private final MessageHelper messageHelper;
44  
45  	/**
46  	 * コンストラクタ
47  	 */
48  	public NumberValidator() {
49  		this("valid.number");
50  	}
51  
52  	/**
53  	 * エラーメッセージキーを指定するコンストラクタ
54  	 * 
55  	 * @param messageKey
56  	 *            エラーメッセージキー
57  	 */
58  	public NumberValidator(final String messageKey) {
59  		this.messageHelper = new MessageHelper(messageKey);
60  	}
61  
62  	/**
63  	 * {@inheritDoc}
64  	 */
65  	public void validate(final ValidationContext context, final Object value) {
66  		if (value instanceof String) {
67  			final String str = (String) value;
68  			if (StringUtil.isEmpty(str)) {
69  				return;
70  			}
71  			try {
72  				new BigDecimal(str);
73  				return;
74  			} catch (final NumberFormatException e) {
75  			}
76  		} else if (value == null) {
77  			return;
78  		}
79  		context.addMessageInfo(this.messageHelper.createMessageInfo());
80  	}
81  
82  }