1 | |
package org.seasar.cubby.validator.validators; |
2 | |
|
3 | |
import java.util.regex.Matcher; |
4 | |
import java.util.regex.Pattern; |
5 | |
|
6 | |
import org.seasar.cubby.validator.BaseValidator; |
7 | |
import org.seasar.cubby.validator.ValidationContext; |
8 | |
import org.seasar.framework.util.StringUtil; |
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
public class RegexpValidator extends BaseValidator { |
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
private final Pattern pattern; |
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
public RegexpValidator(final String regex) { |
27 | 1 | this(regex, "valid.regexp"); |
28 | 1 | } |
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
|
35 | 1 | public RegexpValidator(final String regex, final String messageKey) { |
36 | 1 | this.pattern = Pattern.compile(regex); |
37 | 1 | this.setMessageKey(messageKey); |
38 | 1 | } |
39 | |
|
40 | |
public String validate(final ValidationContext ctx) { |
41 | 4 | final Object value = ctx.getValue(); |
42 | 4 | if (value == null) { |
43 | 1 | return null; |
44 | |
} |
45 | 3 | if (value instanceof String) { |
46 | 3 | String stringValue = (String) value; |
47 | 3 | if (StringUtil.isEmpty(stringValue)) { |
48 | 1 | return null; |
49 | |
} |
50 | 2 | Matcher matcher = pattern.matcher(stringValue); |
51 | 2 | if (matcher.matches()) { |
52 | 1 | return null; |
53 | |
} |
54 | |
} |
55 | 1 | return getMessage(getPropertyMessage(ctx.getName())); |
56 | |
} |
57 | |
|
58 | |
} |