Created
February 23, 2022 15:08
-
-
Save dorosch/1db6070ab9ec931079ce06003bebb334 to your computer and use it in GitHub Desktop.
Base validator class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import abc | |
from django.core.exceptions import ValidationError | |
class BaseValidator(abc.ABC): | |
""" | |
Base validator class for collect and run validations. | |
Every method starting with 'validate_' will be considered validation. | |
The validation method must fail with an error. Examlpe: | |
>>> class MyValidator(BaseValidator): | |
... def validate_something(self): | |
... raise ValidationError() | |
... | |
>>> errors = MyValidator().validate(raise_exceptions=True) | |
""" | |
def __init__(self, *args, **kwargs): | |
self.errors = [] | |
def _get_validators(self): | |
return [ | |
getattr(self, attr) | |
for attr in dir(self) if attr.startswith('validate_') | |
] | |
def validate(self, raise_exceptions=False): | |
for validation in self._get_validators(): | |
try: | |
validation() | |
except ValidationError as error: | |
self.errors.append(error) | |
if self.errors and raise_exceptions: | |
raise ValidationError(self.errors) | |
return self.errors | |
def is_valid(self): | |
return not self.errors | |
@property | |
def errors_dict(self): | |
return [ | |
{key: messages} | |
for error in self.errors | |
for key, messages in error.message_dict.items() | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment