| 299 | def 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 | |
| 307 | def 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 | |
| 500 | |
| 501 | |
| 502 | class 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) |