View Javadoc

1   package org.seasar.cubby.validator.validators;
2   
3   import java.math.BigDecimal;
4   
5   import org.seasar.cubby.validator.BaseValidator;
6   import org.seasar.cubby.validator.ValidationContext;
7   import org.seasar.framework.util.StringUtil;
8   
9   /**
10   * 数値かどうかを検証します。<p>
11   * 数値かどうかの検証は「new BigDecimal(str);」で行っています。
12   * @author agata
13   * @see BigDecimal
14   */
15  public class NumberValidator extends BaseValidator {
16  
17  	/**
18  	 * コンストラクタ
19  	 */
20  	public NumberValidator() {
21  		this("valid.number");
22  	}
23  
24  	/**
25  	 * エラーメッセージキーを指定するコンストラクタ
26  	 * @param messageKey エラーメッセージキー
27  	 */
28  	public NumberValidator(final String messageKey) {
29  		this.setMessageKey(messageKey);
30  	}
31  
32  	public String validate(final ValidationContext ctx) {
33  		final Object value = ctx.getValue();
34  		if (value instanceof String) {
35  			String str = (String)value;
36  			if (StringUtil.isEmpty(str)) {
37  				return null;
38  			}
39  			try {
40  				new BigDecimal(str);
41  				return null;
42  			} catch (NumberFormatException e) {}
43  		}else if(value == null){
44  			return null;
45  		}
46  		return getMessage(getPropertyMessage(ctx.getName()));
47  	}
48  }