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  import org.apache.commons.lang3.StringUtils;
26  
27  import java.util.regex.Matcher;
28  import java.util.regex.Pattern;
29  
30  /**
31   * Validator for EU VAT number.
32   *
33   * @author Jean Couteau - couteau@codelutin.com
34   * @since 2.3
35   */
36  public class VATIdentificationNumberFieldValidator extends NuitonFieldValidatorSupport {
37  
38      protected static String VAT_INTRA_REGEXP = "^(RO\\d{2,10}|GB\\d{5}|(ATU|DK|FI|HU|LU|MT|CZ|SI)\\d{8}|IE[A-Z\\d]{8}|(DE|BG|EE|EL|LT|BE0|PT|CZ)\\d{9}|CY\\d{8}[A-Z]|(ES|GB)[A-Z\\d]{9}|(BE0|PL|SK|CZ)\\d{10}|(FR|IT|LV)\\d{11}|(LT|SE)\\d{12}|(NL|GB)[A-Z\\d]{12})$";
39  
40      protected static Pattern p = Pattern.compile(VAT_INTRA_REGEXP);
41  
42      @Override
43      public void validateWhenNotSkip(Object object) throws ValidationException {
44  
45          String fieldName = getFieldName();
46          Object value = getFieldValue(fieldName, object);
47  
48          if (value == null) {
49              // no value defined
50              return;
51          }
52          if (value instanceof String) {
53  
54              String vatNumber = (String) value;
55              if (StringUtils.isEmpty(vatNumber)) {
56                  // no value defined
57                  return;
58              }
59  
60              // Remove any space
61              vatNumber = vatNumber.replaceAll(" ", "");
62  
63              Matcher m = p.matcher(vatNumber);
64              if (!m.matches()) {
65                  addFieldError(fieldName, object);
66              }
67          } else {
68              addFieldError(fieldName, object);
69          }
70      }
71  
72      @Override
73      public String getValidatorType() {
74          return "VATIdentificationNumber";
75      }
76  }