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