View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.validator;
18  
19  import java.util.regex.Matcher;
20  import java.util.regex.Pattern;
21  
22  import org.apache.commons.validator.routines.InetAddressValidator;
23  
24  /**
25   * <p>Perform email validations.</p>
26   * <p>
27   * This class is a Singleton; you can retrieve the instance via the getInstance() method.
28   * </p>
29   * <p>
30   * Based on a script by <a href="mailto:stamhankar@hotmail.com">Sandeep V. Tamhankar</a>
31   * http://javascript.internet.com
32   * </p>
33   * <p>
34   * This implementation is not guaranteed to catch all possible errors in an email address.
35   * For example, an address like nobody@noplace.somedog will pass validator, even though there
36   * is no TLD "somedog"
37   * </p>.
38   *
39   * @since 1.1
40   * @deprecated Use the new EmailValidator in the routines package. This class
41   * will be removed in a future release.
42   */
43  @Deprecated
44  public class EmailValidator {
45  
46      private static final String SPECIAL_CHARS = "\\p{Cntrl}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]";
47      private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
48      private static final String QUOTED_USER = "(\"[^\"]*\")";
49      private static final String ATOM = VALID_CHARS + '+';
50      private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")";
51  
52  // NOT USED   private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
53  // NOT USED   private static final Pattern EMAIL_PATTERN = Pattern.compile("^(.+)@(.+)$");
54      private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile("^\\[(.*)\\]$");
55      private static final Pattern TLD_PATTERN = Pattern.compile("^([a-zA-Z]+)$");
56  
57      private static final Pattern USER_PATTERN = Pattern.compile("^\\s*" + WORD + "(\\." + WORD + ")*$");
58      private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*\\s*$");
59      private static final Pattern ATOM_PATTERN = Pattern.compile("(" + ATOM + ")");
60  
61      /**
62       * Singleton instance of this class.
63       */
64      private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator();
65  
66      /**
67       * Returns the Singleton instance of this validator.
68       * @return singleton instance of this validator.
69       */
70      public static EmailValidator getInstance() {
71          return EMAIL_VALIDATOR;
72      }
73  
74      /**
75       * Protected constructor for subclasses to use.
76       */
77      protected EmailValidator() {
78      }
79  
80      /**
81       * <p>Checks if a field has a valid e-mail address.</p>
82       *
83       * @param email The value validation is being performed on.  A <code>null</code>
84       * value is considered invalid.
85       * @return true if the email address is valid.
86       */
87      public boolean isValid(final String email) {
88          return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email);
89      }
90  
91      /**
92       * Returns true if the domain component of an email address is valid.
93       * @param domain being validated.
94       * @return true if the email address's domain is valid.
95       */
96      protected boolean isValidDomain(final String domain) {
97          boolean symbolic = false;
98  
99          // see if domain is an IP address in brackets
100         final Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain);
101 
102         if (ipDomainMatcher.matches()) {
103             final InetAddressValidator inetAddressValidator =
104                     InetAddressValidator.getInstance();
105             if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) {
106                 return true;
107             }
108         } else {
109             // Domain is symbolic name
110             symbolic = DOMAIN_PATTERN.matcher(domain).matches();
111         }
112 
113         if (!symbolic) {
114             return false;
115         }
116         if (!isValidSymbolicDomain(domain)) {
117             return false;
118         }
119 
120         return true;
121     }
122 
123     /**
124      * Validates an IP address. Returns true if valid.
125      * @param ipAddress IP address
126      * @return true if the ip address is valid.
127      */
128     protected boolean isValidIpAddress(final String ipAddress) {
129         final Matcher ipAddressMatcher = IP_DOMAIN_PATTERN.matcher(ipAddress);
130         for (int i = 1; i <= 4; i++) { // CHECKSTYLE IGNORE MagicNumber
131             final String ipSegment = ipAddressMatcher.group(i);
132             if (ipSegment == null || ipSegment.isEmpty()) {
133                 return false;
134             }
135 
136             int iIpSegment = 0;
137 
138             try {
139                 iIpSegment = Integer.parseInt(ipSegment);
140             } catch (final NumberFormatException e) {
141                 return false;
142             }
143 
144             if (iIpSegment > 255) { // CHECKSTYLE IGNORE MagicNumber
145                 return false;
146             }
147 
148         }
149         return true;
150     }
151 
152     /**
153      * Validates a symbolic domain name.  Returns true if it's valid.
154      * @param domain symbolic domain name
155      * @return true if the symbolic domain name is valid.
156      */
157     protected boolean isValidSymbolicDomain(String domain) {
158         final String[] domainSegment = new String[10]; // CHECKSTYLE IGNORE MagicNumber
159         boolean match = true;
160         int i = 0;
161         final Matcher atomMatcher = ATOM_PATTERN.matcher(domain);
162         while (match) {
163             match = atomMatcher.matches();
164             if (match) {
165                 domainSegment[i] = atomMatcher.group(1);
166                 final int l = domainSegment[i].length() + 1;
167                 domain =
168                         l >= domain.length()
169                         ? ""
170                         : domain.substring(l);
171 
172                 i++;
173             }
174         }
175 
176         final int len = i;
177 
178         // Make sure there's a host name preceding the domain.
179         if (len < 2) {
180             return false;
181         }
182 
183         final String tld = domainSegment[len - 1];
184         if (tld.length() <= 1) {
185             return false;
186         }
187         if (! TLD_PATTERN.matcher(tld).matches()) {
188             return false;
189         }
190 
191         return true;
192     }
193 
194     /**
195      * Returns true if the user component of an email address is valid.
196      * @param user being validated
197      * @return true if the user name is valid.
198      */
199     protected boolean isValidUser(final String user) {
200         return USER_PATTERN.matcher(user).matches();
201     }
202 
203     /**
204      * Recursively remove comments, and replace with a single space. The simpler regexps in the Email Addressing FAQ are imperfect - they will miss escaped
205      * chars in atoms, for example. Derived From Mail::RFC822::Address
206      * 
207      * @param emailStr The email address
208      * @return address with comments removed.
209      */
210     protected String stripComments(final String emailStr) {
211         String result = emailStr;
212         final String commentPat = "^((?:[^\"\\\\]|\\\\.)*(?:\"(?:[^\"\\\\]|\\\\.)*\"(?:[^\"\\\\]|\111111\\\\.)*)*)\\((?:[^()\\\\]|\\\\.)*\\)/";
213         final Pattern commentMatcher = Pattern.compile(commentPat);
214 
215         while (commentMatcher.matcher(result).matches()) {
216             result = result.replaceFirst(commentPat, "\1 ");
217         }
218         return result;
219     }
220 }