1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.seasar.cubby.validator.validators;
18
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 import org.seasar.cubby.action.MessageInfo;
23 import org.seasar.cubby.internal.util.StringUtils;
24 import org.seasar.cubby.validator.ScalarFieldValidator;
25 import org.seasar.cubby.validator.ValidationContext;
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 public class RegexpValidator implements ScalarFieldValidator {
51
52
53
54
55 private final String messageKey;
56
57
58
59
60 private final Pattern pattern;
61
62
63
64
65
66
67
68 public RegexpValidator(final String regex) {
69 this(regex, "valid.regexp");
70 }
71
72
73
74
75
76
77
78
79
80 public RegexpValidator(final String regex, final String messageKey) {
81 this(Pattern.compile(regex), messageKey);
82 }
83
84
85
86
87
88
89
90 public RegexpValidator(final Pattern pattern) {
91 this(pattern, "valid.regexp");
92 }
93
94
95
96
97
98
99
100
101
102 public RegexpValidator(final Pattern pattern, final String messageKey) {
103 this.pattern = pattern;
104 this.messageKey = messageKey;
105 }
106
107
108
109
110 public void validate(final ValidationContext context, final Object value) {
111 if (value == null) {
112 return;
113 }
114 if (value instanceof String) {
115 final String stringValue = (String) value;
116 if (StringUtils.isEmpty(stringValue)) {
117 return;
118 }
119 final Matcher matcher = pattern.matcher(stringValue);
120 if (matcher.matches()) {
121 return;
122 }
123 }
124
125 final MessageInfo messageInfo = new MessageInfo();
126 messageInfo.setKey(this.messageKey);
127 context.addMessageInfo(messageInfo);
128 }
129
130 }