1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 """Used to validate the length of strings."""
17
18 from muntjac.data.validators.abstract_validator import AbstractValidator
19
20
22 """This StringLengthValidator is used to validate the length of strings.
23
24 @author: Vaadin Ltd.
25 @author: Richard Lincoln
26 @version: 1.1.2
27 """
28
29 - def __init__(self, errorMessage, minLength=None, maxLength=None,
30 allowNull=None):
31 """Creates a new StringLengthValidator with a given error message,
32 permissable lengths and null-string allowance.
33
34 @param errorMessage:
35 the message to display in case the value does not validate.
36 @param minLength:
37 the minimum permissible length of the string.
38 @param maxLength:
39 the maximum permissible length of the string.
40 @param allowNull:
41 Are null strings permissible? This can be handled better by
42 setting a field as required or not.
43 """
44 self._minLength = -1
45 self._maxLength = -1
46 self._allowNull = True
47
48 if minLength is None:
49 super(StringLengthValidator, self).__init__(errorMessage)
50 else:
51 StringLengthValidator.__init__(self, errorMessage)
52 self.setMinLength(minLength)
53 self.setMaxLength(maxLength)
54 self.setNullAllowed(allowNull)
55
56
58 """Checks if the given value is valid.
59
60 @param value:
61 the value to validate.
62 @return: C{True} for valid value, otherwise C{False}.
63 """
64 if value is None:
65 return self._allowNull
66
67 s = str(value)
68 if s is None:
69 return self._allowNull
70
71 length = len(s)
72 if (self._minLength >= 0 and length < self._minLength) \
73 or (self._maxLength >= 0 and length > self._maxLength):
74 return False
75
76 return True
77
78
80 """Returns C{True} if null strings are allowed.
81
82 @return: C{True} if allows null string, otherwise C{False}.
83 """
84 return self._allowNull
85
86
88 """Gets the maximum permissible length of the string.
89
90 @return: the maximum length of the string.
91 """
92 return self._maxLength
93
94
96 """Gets the minimum permissible length of the string.
97
98 @return: the minimum length of the string.
99 """
100 return self._minLength
101
102
104 """Sets whether null-strings are to be allowed. This can be better
105 handled by setting a field as required or not.
106 """
107 self._allowNull = allowNull
108
109
111 """Sets the maximum permissible length of the string.
112
113 @param maxLength:
114 the length to set.
115 """
116 if maxLength < -1:
117 maxLength = -1
118
119 self._maxLength = maxLength
120
121
123 """Sets the minimum permissible length.
124
125 @param minLength:
126 the length to set.
127 """
128 if minLength < -1:
129 minLength = -1
130
131 self._minLength = minLength
132