|
| 1 | +from django.core.exceptions import ValidationError |
| 2 | +from django.core import validators |
| 3 | + |
| 4 | +# NOTE: As this module may be imported by configuration.py, we cannot import |
| 5 | +# anything from NetBox itself. |
| 6 | + |
| 7 | + |
| 8 | +class IsEmptyValidator: |
| 9 | + """ |
| 10 | + Employed by CustomValidator to enforce required fields. |
| 11 | + """ |
| 12 | + message = "This field must be empty." |
| 13 | + code = 'is_empty' |
| 14 | + |
| 15 | + def __init__(self, enforce=True): |
| 16 | + self._enforce = enforce |
| 17 | + |
| 18 | + def __call__(self, value): |
| 19 | + if self._enforce and value not in validators.EMPTY_VALUES: |
| 20 | + raise ValidationError(self.message, code=self.code) |
| 21 | + |
| 22 | + |
| 23 | +class IsNotEmptyValidator: |
| 24 | + """ |
| 25 | + Employed by CustomValidator to enforce prohibited fields. |
| 26 | + """ |
| 27 | + message = "This field must not be empty." |
| 28 | + code = 'not_empty' |
| 29 | + |
| 30 | + def __init__(self, enforce=True): |
| 31 | + self._enforce = enforce |
| 32 | + |
| 33 | + def __call__(self, value): |
| 34 | + if self._enforce and value in validators.EMPTY_VALUES: |
| 35 | + raise ValidationError(self.message, code=self.code) |
| 36 | + |
| 37 | + |
| 38 | +class CustomValidator: |
| 39 | + """ |
| 40 | + This class enables the application of user-defined validation rules to NetBox models. It can be instantiated by |
| 41 | + passing a dictionary of validation rules in the form {attribute: rules}, where 'rules' is a dictionary mapping |
| 42 | + descriptors (e.g. min_length or regex) to values. |
| 43 | +
|
| 44 | + A CustomValidator instance is applied by calling it with the instance being validated: |
| 45 | +
|
| 46 | + validator = CustomValidator({'name': {'min_length: 10}}) |
| 47 | + site = Site(name='abcdef') |
| 48 | + validator(site) # Raises ValidationError |
| 49 | +
|
| 50 | + :param validation_rules: A dictionary mapping object attributes to validation rules |
| 51 | + """ |
| 52 | + VALIDATORS = { |
| 53 | + 'min': validators.MinValueValidator, |
| 54 | + 'max': validators.MaxValueValidator, |
| 55 | + 'min_length': validators.MinLengthValidator, |
| 56 | + 'max_length': validators.MaxLengthValidator, |
| 57 | + 'regex': validators.RegexValidator, |
| 58 | + 'required': IsNotEmptyValidator, |
| 59 | + 'prohibited': IsEmptyValidator, |
| 60 | + } |
| 61 | + |
| 62 | + def __init__(self, validation_rules=None): |
| 63 | + self.validation_rules = validation_rules or {} |
| 64 | + assert type(self.validation_rules) is dict, "Validation rules must be passed as a dictionary" |
| 65 | + |
| 66 | + def __call__(self, instance): |
| 67 | + # Validate instance attributes per validation rules |
| 68 | + for attr_name, rules in self.validation_rules.items(): |
| 69 | + assert hasattr(instance, attr_name), f"Invalid attribute '{attr_name}' for {instance.__class__.__name__}" |
| 70 | + attr = getattr(instance, attr_name) |
| 71 | + for descriptor, value in rules.items(): |
| 72 | + validator = self.get_validator(descriptor, value) |
| 73 | + try: |
| 74 | + validator(attr) |
| 75 | + except ValidationError as exc: |
| 76 | + # Re-package the raised ValidationError to associate it with the specific attr |
| 77 | + raise ValidationError({attr_name: exc}) |
| 78 | + |
| 79 | + # Execute custom validation logic (if any) |
| 80 | + self.validate(instance) |
| 81 | + |
| 82 | + def get_validator(self, descriptor, value): |
| 83 | + """ |
| 84 | + Instantiate and return the appropriate validator based on the descriptor given. For |
| 85 | + example, 'min' returns MinValueValidator(value). |
| 86 | + """ |
| 87 | + if descriptor not in self.VALIDATORS: |
| 88 | + raise NotImplementedError( |
| 89 | + f"Unknown validation type for {self.__class__.__name__}: '{descriptor}'" |
| 90 | + ) |
| 91 | + validator_cls = self.VALIDATORS.get(descriptor) |
| 92 | + return validator_cls(value) |
| 93 | + |
| 94 | + def validate(self, instance): |
| 95 | + """ |
| 96 | + Custom validation method, to be overridden by the user. Validation failures should |
| 97 | + raise a ValidationError exception. |
| 98 | + """ |
| 99 | + return |
| 100 | + |
| 101 | + def fail(self, message, field=None): |
| 102 | + """ |
| 103 | + Raise a ValidationError exception. Associate the provided message with a form/serializer field if specified. |
| 104 | + """ |
| 105 | + if field is not None: |
| 106 | + raise ValidationError({field: message}) |
| 107 | + raise ValidationError(message) |
0 commit comments