1
2
3
4 package org.mod4j.runtime.validation;
5
6 import org.springframework.validation.Errors;
7 import org.springframework.validation.Validator;
8
9
10
11
12 public class RegExpValidator implements Validator {
13
14 private String field;
15
16 private String regExp;
17
18 private Class clazz;
19
20
21
22
23
24
25
26 public RegExpValidator(Class clazz, String field, String regExp) {
27 this.clazz = clazz;
28 this.field = field;
29 this.regExp = regExp;
30 }
31
32
33
34
35 @SuppressWarnings("unchecked")
36 public boolean supports(Class clazz) {
37 return this.clazz.isAssignableFrom(clazz);
38 }
39
40
41
42
43 public void validate(Object target, Errors errors) {
44
45 String value = (String) errors.getFieldValue(field);
46 if (value != null) {
47
48 if (!value.matches(regExp)) {
49 errors.rejectValue(field, "field.regexp.match", new String[] { value, regExp },
50 field + " with value '" + value + "' does not match regular expression " + regExp);
51 }
52 }
53 }
54
55 }