01: package org.conform.validator;
02:
03: import org.conform.Validator;
04: import org.conform.ValidationException;
05:
06: import java.util.regex.*;
07: import java.lang.annotation.Annotation;
08:
09: public class RegularExpressionValidator implements Validator {
10: private String expression = ".*";
11: private String message = "validation.does_not_match";
12: private Pattern pattern;
13:
14: public RegularExpressionValidator() {
15: }
16:
17: public RegularExpressionValidator(Annotation annotation) {
18: RegularExpression regularExpression = (RegularExpression) annotation;
19: switch (regularExpression.type()) {
20: case CUSTOM:
21: expression = regularExpression.expression();
22: break;
23: default:
24: expression = regularExpression.type().getExpression();
25: }
26: }
27:
28: public void setExpression(String expression) {
29: this .expression = expression;
30: pattern = Pattern.compile(expression);
31: }
32:
33: public String getExpression() {
34: return expression;
35: }
36:
37: public void setMessage(String message) {
38: this .message = message;
39: }
40:
41: public String getMessage() {
42: return message;
43: }
44:
45: public Object validate(Object value) {
46: if (expression == null || expression.length() == 0)
47: return value;
48:
49: if (value == null)
50: value = "";
51:
52: Matcher matcher = pattern.matcher(value.toString());
53:
54: if (!matcher.matches())
55: throw new ValidationException(
56: new ValidationException.Message(getMessage(),
57: new Object[] { value }));
58: return value;
59: }
60: }
|