1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
29
30
31
32
33
34
35
36
37
38
39 public class NumberValidator implements ScalarFieldValidator {
40
41 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 this("valid.number");
53 }
54
55
56
57
58
59
60
61 public NumberValidator(final String messageKey) {
62 this.messageHelper = new MessageHelper(messageKey);
63 }
64
65
66
67
68 public void validate(final ValidationContext context, final Object value) {
69 if (value instanceof String) {
70 final String str = (String) value;
71 if (StringUtils.isEmpty(str)) {
72 return;
73 }
74 if (NUMBER_PATTERN.matcher(str).find()) {
75 return;
76 }
77 } else if (value == null) {
78 return;
79 }
80 context.addMessageInfo(this.messageHelper.createMessageInfo());
81 }
82
83 }