From 303e34299af7d383598db98ca02df19ca798d5f7 Mon Sep 17 00:00:00 2001 From: Roberto Rosario Date: Mon, 1 Jul 2019 09:41:45 -0400 Subject: [PATCH] Add a JSON and YAML validator to the common app Signed-off-by: Roberto Rosario --- mayan/apps/common/validators.py | 57 +++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/mayan/apps/common/validators.py b/mayan/apps/common/validators.py index 84ff982615..97a4db3326 100644 --- a/mayan/apps/common/validators.py +++ b/mayan/apps/common/validators.py @@ -1,9 +1,18 @@ from __future__ import unicode_literals +import json import re +import yaml +try: + from yaml import CSafeLoader as SafeLoader +except ImportError: + from yaml import SafeLoader + +from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.utils import six +from django.utils.deconstruct import deconstructible from django.utils.functional import SimpleLazyObject from django.utils.translation import ugettext_lazy as _ @@ -23,6 +32,54 @@ def _lazy_re_compile(regex, flags=0): return SimpleLazyObject(_compile) +@deconstructible +class JSONValidator(object): + """ + Validates that the input is JSON compliant. + """ + def __call__(self, value): + value = value.strip() + try: + json.loads(stream=value) + except ValueError: + raise ValidationError( + _('Enter a valid JSON value.'), + code='invalid' + ) + + def __eq__(self, other): + return ( + isinstance(other, JSONValidator) + ) + + def __ne__(self, other): + return not (self == other) + + +@deconstructible +class YAMLValidator(object): + """ + Validates that the input is YAML compliant. + """ + def __call__(self, value): + value = value.strip() + try: + yaml.load(stream=value, Loader=SafeLoader) + except yaml.error.YAMLError: + raise ValidationError( + _('Enter a valid YAML value.'), + code='invalid' + ) + + def __eq__(self, other): + return ( + isinstance(other, YAMLValidator) + ) + + def __ne__(self, other): + return not (self == other) + + internal_name_re = _lazy_re_compile(r'^[a-zA-Z0-9_]+\Z') validate_internal_name = RegexValidator( internal_name_re, _(