Package muntjac :: Package data :: Package validators :: Module composite_validator
[hide private]
[frames] | no frames]

Source Code for Module muntjac.data.validators.composite_validator

  1  # Copyright (C) 2012 Vaadin Ltd.  
  2  # Copyright (C) 2012 Richard Lincoln 
  3  #  
  4  # Licensed under the Apache License, Version 2.0 (the "License");  
  5  # you may not use this file except in compliance with the License.  
  6  # You may obtain a copy of the License at  
  7  #  
  8  #     http://www.apache.org/licenses/LICENSE-2.0  
  9  #  
 10  # Unless required by applicable law or agreed to in writing, software  
 11  # distributed under the License is distributed on an "AS IS" BASIS,  
 12  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 13  # See the License for the specific language governing permissions and  
 14  # limitations under the License. 
 15   
 16  """Allows you to chain (compose) many validators to validate one field.""" 
 17   
 18  from muntjac.data.validators.abstract_validator import AbstractValidator 
 19  from muntjac.data.validator import InvalidValueException 
 20   
 21   
22 -class CompositeValidator(AbstractValidator):
23 """The C{CompositeValidator} allows you to chain (compose) many 24 validators to validate one field. The contained validators may be required 25 to all validate the value to validate or it may be enough that one 26 contained validator validates the value. This behaviour is controlled by 27 the modes C{AND} and C{OR}. 28 29 @author: Vaadin Ltd. 30 @author: Richard Lincoln 31 @version: 1.1.2 32 """ 33 34 #: The validators are combined with C{AND} clause: validity of 35 # the composite implies validity of the all validators it is composed of 36 # must be valid. 37 MODE_AND = 0 38 39 #: The validators are combined with C{OR} clause: validity of the 40 # composite implies that some of validators it is composed of must be 41 # valid. 42 MODE_OR = 1 43 44 #: The validators are combined with and clause: validity of the composite 45 # implies validity of the all validators it is composed of 46 MODE_DEFAULT = MODE_AND 47
48 - def __init__(self, mode=None, errorMessage=None):
49 """Constructs a composite validator in given mode. 50 """ 51 #: Operation mode. 52 self._mode = self.MODE_DEFAULT 53 54 #: List of contained validators. 55 self._validators = list() 56 57 if mode is None: 58 super(CompositeValidator, self).__init__('') 59 else: 60 super(CompositeValidator, self).__init__(errorMessage) 61 self.setMode(mode)
62 63
64 - def validate(self, value):
65 """Validates the given value. 66 67 The value is valid, if: 68 - C{MODE_AND}: All of the sub-validators are valid 69 - C{MODE_OR}: Any of the sub-validators are valid 70 71 If the value is invalid, validation error is thrown. If the error 72 message is set (non-null), it is used. If the error message has not 73 been set, the first error occurred is thrown. 74 75 @param value: 76 the value to check. 77 @raise InvalidValueException: 78 if the value is not valid. 79 """ 80 if self._mode == self.MODE_AND: 81 for validator in self._validators: 82 validator.validate(value) 83 return 84 elif self._mode == self.MODE_OR: 85 first = None 86 for v in self._validators: 87 try: 88 v.validate(value) 89 return 90 except InvalidValueException, e: 91 if first is None: 92 first = e 93 if first is None: 94 return 95 em = self.getErrorMessage() 96 if em is not None: 97 raise InvalidValueException(em) 98 else: 99 raise first 100 101 raise ValueError, 'The validator is in unsupported operation mode'
102 103
104 - def isValid(self, value):
105 """Checks the validity of the the given value. The value is valid, if: 106 - C{MODE_AND}: All of the sub-validators are valid 107 - C{MODE_OR}: Any of the sub-validators are valid 108 109 @param value: 110 the value to check. 111 """ 112 if self._mode == self.MODE_AND: 113 for v in self._validators: 114 if not v.isValid(value): 115 return False 116 return True 117 118 elif self._mode == self.MODE_OR: 119 for v in self._validators: 120 if v.isValid(value): 121 return True 122 return False 123 124 raise ValueError, 'The valitor is in unsupported operation mode'
125 126
127 - def getMode(self):
128 """Gets the mode of the validator. 129 130 @return: Operation mode of the validator: C{MODE_AND} or C{MODE_OR}. 131 """ 132 return self._mode
133 134
135 - def setMode(self, mode):
136 """Sets the mode of the validator. The valid modes are: 137 - C{MODE_AND} (default) 138 - C{MODE_OR} 139 140 @param mode: 141 the mode to set. 142 """ 143 if mode != self.MODE_AND and mode != self.MODE_OR: 144 raise ValueError, 'Mode ' + mode + ' unsupported' 145 146 self._mode = mode
147 148
149 - def getErrorMessage(self):
150 """Gets the error message for the composite validator. If the error 151 message is C{None}, original error messages of the sub-validators are 152 used instead. 153 """ 154 if super(CompositeValidator, self).getErrorMessage() is not None: 155 return super(CompositeValidator, self).getErrorMessage() 156 157 # TODO: return composite error message 158 159 return None
160 161
162 - def addValidator(self, validator):
163 """Adds validator to the interface. 164 165 @param validator: 166 the Validator object which performs validation checks on 167 this set of data field values. 168 """ 169 if validator is None: 170 return 171 172 self._validators.append(validator)
173 174
175 - def removeValidator(self, validator):
176 """Removes a validator from the composite. 177 178 @param validator: 179 the Validator object which performs validation checks on 180 this set of data field values. 181 """ 182 self._validators.remove(validator)
183 184
185 - def getSubValidators(self, validatorType):
186 """Gets sub-validators by class. 187 188 If the component contains directly or recursively (it contains another 189 composite containing the validator) validators compatible with given 190 type they are returned. This only applies to C{AND} mode composite 191 validators. 192 193 If the validator is in C{OR} mode or does not contain any validators 194 of given type null is returned. 195 196 @return: iterable of validators compatible with given type 197 that must apply or null if none found. 198 """ 199 if self._mode != self.MODE_AND: 200 return None 201 202 found = set() 203 for v in self._validators: 204 if issubclass(v.__class__, validatorType): 205 found.add(v) 206 207 if (isinstance(v, CompositeValidator) 208 and v.getMode() == self.MODE_AND): 209 c = v.getSubValidators(validatorType) 210 if c is not None: 211 for cc in c: 212 found.add(cc) 213 214 return None if len(found) == 0 else found
215