1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
47
48 private String validChars;
49 private int minLength;
50
51
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
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 }