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 * Validator used to validate French phone numbers like :
31 * - 0000000000
32 * - 00.00.00.00.00
33 * - 00-00-00-00-00
34 * - 00 00 00 00 00
35 *
36 * @author Jean Couteau - couteau@codelutin.com
37 * @since 2.3
38 */
39 public class FrenchPhoneNumberFieldValidator extends NuitonFieldValidatorSupport {
40
41 protected static String PHONE_NUMBER_REGEXP =
42 "[0-9]{10}|(([0-9]{2}[-\\.\\s]){4})[0-9]{2}";
43
44 protected static Pattern p = Pattern.compile(PHONE_NUMBER_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 "frenchPhoneNumber";
73 }
74 }