View Javadoc

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   * @author Johan Vogelzang
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       * Validator for regular expressions
22       * @param clazz The class that supports validation of regular expressions
23       * @param field The field to validate
24       * @param regExp The regular expression which the the <code>field</code> must apply to
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       * {@inheritDoc}
34       */
35      @SuppressWarnings("unchecked")
36      public boolean supports(Class clazz) {
37          return this.clazz.isAssignableFrom(clazz);
38      }
39  
40      /**
41       * {@inheritDoc}
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  }