Ticket #3250: brian_validators.diff

File brian_validators.diff, 2.5 KB (added by exogen@…, 18 years ago)

adds validators mentioned in #3250

  • .py

    old new  
    296296        if not all_data.get(self.other, False) and not field_data:
    297297            raise ValidationError, self.error_message
    298298
     299def RequiredIfOtherFieldsNotGiven(other_field_names, error_message=None):
     300    if error_message is None:
     301        from django.utils.text import get_text_list
     302        fields = get_text_list(other_field_names)
     303        error_message = gettext_lazy("This field must be given if %s are not given." % fields)
     304    validators = [RequiredIfOtherFieldNotGiven(field) for field in other_field_names]
     305    return AllValidators(validators, error_message)
     306
     307def RequiredIfAllOtherFieldsNotGiven(other_field_names, error_message=None):
     308    if error_message is None:
     309        from django.utils.text import get_text_list
     310        fields = get_text_list(other_field_names, 'and')
     311        error_message = gettext_lazy("This field must be given if %s are not given." % fields)
     312    validators = [RequiredIfOtherFieldNotGiven(field) for field in other_field_names]
     313    return AnyValidator(validators, error_message)
     314
    299315class RequiredIfOtherFieldsGiven(object):
    300316    def __init__(self, other_field_names, error_message=gettext_lazy("Please enter both fields or leave them both empty.")):
    301317        self.other, self.error_message = other_field_names, error_message
     
    481497            except ValidationError, e:
    482498                pass
    483499        raise ValidationError(self.error_message)
     500
     501
     502class AllValidators(object):
     503    """
     504    This validator tries all given validators. If all of them succeed,
     505    validation passes. If any of them do not succeed, the given message is
     506    thrown as a validation error. The message is rather unspecific, so it's
     507    best to specify one on instantiation.
     508    """
     509    def __init__(self, validator_list=None, error_message=gettext_lazy("This field is invalid.")):
     510        if validator_list is None: validator_list = []
     511        self.validator_list = validator_list
     512        self.error_message = error_message
     513        for v in validator_list:
     514            if hasattr(v, 'always_test'):
     515                self.always_test = True
     516
     517    def __call__(self, field_data, all_data):
     518        for v in self.validator_list:
     519            try:
     520                v(field_data, all_data)
     521            except ValidationError, e:
     522                raise ValidationError(self.error_message)
    484523
    485524class URLMimeTypeCheck(object):
    486525    "Checks that the provided URL points to a document with a listed mime type"
Back to Top