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.util.regex.Matcher;
19 import java.util.regex.Pattern;
20
21 import org.seasar.cubby.action.MessageInfo;
22 import org.seasar.cubby.internal.util.StringUtils;
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
40
41
42
43
44
45
46
47
48
49 public class RegexpValidator implements ScalarFieldValidator {
50
51
52
53
54 private final String messageKey;
55
56
57
58
59 private final Pattern pattern;
60
61
62
63
64
65
66
67 public RegexpValidator(final String regex) {
68 this(regex, "valid.regexp");
69 }
70
71
72
73
74
75
76
77
78
79 public RegexpValidator(final String regex, final String messageKey) {
80 this(Pattern.compile(regex), messageKey);
81 }
82
83
84
85
86
87
88
89 public RegexpValidator(final Pattern pattern) {
90 this(pattern, "valid.regexp");
91 }
92
93
94
95
96
97
98
99
100
101 public RegexpValidator(final Pattern pattern, final String messageKey) {
102 this.pattern = pattern;
103 this.messageKey = messageKey;
104 }
105
106
107
108
109 public void validate(final ValidationContext context, final Object value) {
110 if (value == null) {
111 return;
112 }
113 if (value instanceof String) {
114 final String stringValue = (String) value;
115 if (StringUtils.isEmpty(stringValue)) {
116 return;
117 }
118 final Matcher matcher = pattern.matcher(stringValue);
119 if (matcher.matches()) {
120 return;
121 }
122 }
123
124 final MessageInfo messageInfo = new MessageInfo();
125 messageInfo.setKey(this.messageKey);
126 context.addMessageInfo(messageInfo);
127 }
128
129 }