View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  package org.xnap.util.prefs;
21  
22  import org.xnap.XNap;
23  import org.xnap.util.StringHelper;
24  
25  /***
26   * A string validator. Makes sure all characters of a string are valid and that
27   * it has a minimum length.
28   */
29  public class StringValidator implements Validator
30  {
31  
32      //--- Constant(s) ---
33  
34      /***
35       * Convenience validator for email addresses.
36       */
37      public static final StringValidator EMAIL
38  		= new StringValidator(StringHelper.EMAIL, 1);
39  
40      /***
41       * Convenience validator for ordinary strings without whitespaces.
42       */
43      public static final StringValidator REGULAR_STRING
44  		= new StringValidator(StringHelper.REGULAR_STRING, 1);
45  
46      //--- Data field(s) ---
47  
48      private String validChars;
49      private int minLength;
50  
51      //--- Constructor(s) ---
52  
53      public StringValidator(String validChars, int minLength)
54      {
55  		this.validChars = validChars;
56  		this.minLength = minLength;
57      }
58  
59      public StringValidator(String validChars)
60      {
61  		this(validChars, 0);
62      }
63  
64      public StringValidator()
65      {
66  		this(null);
67      }
68  
69      //--- Method(s) ---
70  
71      /***
72       * Validates <code>String</code>.
73       * @exception IllegalArgumentException if newValue is invalid.
74       */
75      public void validate(String value)
76      {
77  		if (value == null) {
78  			throw new IllegalArgumentException
79  				(XNap.tr("Value must not be null"));
80  		}
81  
82  		if (value.length() < minLength) {
83  			throw new IllegalArgumentException
84  				(XNap.tr("Value is too short"));
85  		}
86  
87  		if (validChars != null) {
88  			for (int i = 0; i < value.length(); i++) {
89  				if (validChars.indexOf(value.charAt(i)) == -1) {
90  					throw(new IllegalArgumentException
91  						(XNap.tr("Invalid character")));
92  				}
93  			}
94  		}
95      }
96  
97  }