1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.settings;
21
22 import org.xnap.commons.i18n.I18n;
23 import org.xnap.commons.i18n.I18nFactory;
24 import org.xnap.commons.util.StringHelper;
25
26 /***
27 * A string validator. Makes sure all characters of a string are valid and that
28 * it has a minimum length.
29 */
30 public class StringValidator implements Validator {
31
32 private static final I18n i18n = I18nFactory.getI18n(StringValidator.class);
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 private String validChars;
47 private int minLength;
48
49 /***
50 * Constructs a string validator that accepts any String composed of
51 * <code>validChars</code> with a minimum length of
52 * <code>minlength</code> characters.
53 *
54 * @param validChars the allowed characters
55 * @param minLength the minimum length
56 */
57 public StringValidator(String validChars, int minLength)
58 {
59 this.validChars = validChars;
60 this.minLength = minLength;
61 }
62
63 /***
64 * Constructs a string validator that accepts any non-null String
65 * composed of <code>validChars</code>.
66 *
67 * @param validChars the allowed characters
68 */
69 public StringValidator(String validChars)
70 {
71 this(validChars, 0);
72 }
73
74 /***
75 * Constructs a string validator that accepts any non-null String.
76 */
77 public StringValidator()
78 {
79 this(null);
80 }
81
82 public void validate(String value)
83 {
84 if (value == null) {
85 throw new IllegalArgumentException(i18n.tr("Value must not be null"));
86 }
87 else if (value.length() < minLength) {
88 throw new IllegalArgumentException(i18n.tr("Value is too short"));
89 }
90 else if (validChars != null) {
91 for (int i = 0; i < value.length(); i++) {
92 if (validChars.indexOf(value.charAt(i)) == -1) {
93 throw(new IllegalArgumentException(i18n.tr("Invalid character")));
94 }
95 }
96 }
97 }
98
99 }