View Javadoc
1   /*
2    * #%L
3    * Nuiton Validator
4    * %%
5    * Copyright (C) 2013 - 2014 Code Lutin, Tony Chemit
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU Lesser General Public License as 
9    * published by the Free Software Foundation, either version 3 of the 
10   * License, or (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Lesser Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Lesser Public 
18   * License along with this program.  If not, see
19   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
20   * #L%
21   */
22  package org.nuiton.validator.xwork2.field;
23  
24  import com.opensymphony.xwork2.validator.ValidationException;
25  
26  import java.util.regex.Matcher;
27  import java.util.regex.Pattern;
28  
29  /**
30   * Validate post codes for French cities
31   *
32   * - Take into account 2A and 2B
33   * - Take into account DOMs and TOMs
34   * - Postcodes starting with 99 are not valid
35   *
36   * @author Jean Couteau - couteau@codelutin.com
37   * @since 2.3
38   */
39  public class FrenchPostCodeFieldValidator extends NuitonFieldValidatorSupport {
40  
41      protected static String POST_CODE_REGEXP =
42              "^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$";
43  
44      protected static Pattern p = Pattern.compile(POST_CODE_REGEXP);
45  
46      @Override
47      public void validateWhenNotSkip(Object object) throws ValidationException {
48  
49          String fieldName = getFieldName();
50          Object value = getFieldValue(fieldName, object);
51  
52          if (value == null) {
53              // no value defined
54              return;
55          }
56          if (value instanceof String) {
57              if ("".equals(value)) {
58                  // no value defined
59                  return;
60              }
61              Matcher m = p.matcher((String) value);
62              if (!m.matches()) {
63                  addFieldError(fieldName, object);
64              }
65          } else {
66              addFieldError(fieldName, object);
67          }
68      }
69  
70      @Override
71      public String getValidatorType() {
72          return "frenchPostCode";
73      }
74  }