Add a validator to models CharField that should be regular expressions

This commit is contained in:
Valentin Samir 2016-08-21 09:03:32 +02:00
parent 282e3a831b
commit 14a459b128
3 changed files with 31 additions and 3 deletions

View file

@ -466,7 +466,8 @@ class ServicePattern(models.Model):
"A regular expression matching services. " "A regular expression matching services. "
"Will usually looks like '^https://some\\.server\\.com/path/.*$'." "Will usually looks like '^https://some\\.server\\.com/path/.*$'."
"As it is a regular expression, special character must be escaped with a '\\'." "As it is a regular expression, special character must be escaped with a '\\'."
) ),
validators=[utils.regexpr_validator]
) )
#: Name of the attribute to transmit as username, if empty the user login is used #: Name of the attribute to transmit as username, if empty the user login is used
user_field = models.CharField( user_field = models.CharField(
@ -660,7 +661,8 @@ class FilterAttributValue(models.Model):
pattern = models.CharField( pattern = models.CharField(
max_length=255, max_length=255,
verbose_name=_(u"pattern"), verbose_name=_(u"pattern"),
help_text=_(u"a regular expression") help_text=_(u"a regular expression"),
validators=[utils.regexpr_validator]
) )
#: ForeignKey to a :class:`ServicePattern`. :class:`FilterAttributValue` instances for a #: ForeignKey to a :class:`ServicePattern`. :class:`FilterAttributValue` instances for a
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.filters` #: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.filters`
@ -689,7 +691,8 @@ class ReplaceAttributValue(models.Model):
pattern = models.CharField( pattern = models.CharField(
max_length=255, max_length=255,
verbose_name=_(u"pattern"), verbose_name=_(u"pattern"),
help_text=_(u"An regular expression maching whats need to be replaced") help_text=_(u"An regular expression maching whats need to be replaced"),
validators=[utils.regexpr_validator]
) )
#: The replacement to what is mached by :attr:`pattern`. groups are capture by \\1, \\2 … #: The replacement to what is mached by :attr:`pattern`. groups are capture by \\1, \\2 …
replace = models.CharField( replace = models.CharField(

View file

@ -255,3 +255,9 @@ class UtilsTestCase(TestCase):
self.assertIsInstance(result, dict) self.assertIsInstance(result, dict)
self.assertIn('applied', result) self.assertIn('applied', result)
self.assertIsInstance(result['applied'], datetime.datetime) self.assertIsInstance(result['applied'], datetime.datetime)
def test_regexpr_validator(self):
"""test the function regexpr_validator"""
utils.regexpr_validator("^a$")
with self.assertRaises(utils.ValidationError):
utils.regexpr_validator("[")

View file

@ -18,7 +18,10 @@ from django.contrib import messages
from django.contrib.messages import constants as DEFAULT_MESSAGE_LEVELS from django.contrib.messages import constants as DEFAULT_MESSAGE_LEVELS
from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import re
import random import random
import string import string
import json import json
@ -700,3 +703,19 @@ def logout_request(ticket):
'datetime': timezone.now().isoformat(), 'datetime': timezone.now().isoformat(),
'ticket': ticket 'ticket': ticket
} }
def regexpr_validator(value):
"""
Test that ``value`` is a valid regular expression
:param unicode value: A regular expression to test
:raises ValidationError: if ``value`` is not a valid regular expression
"""
try:
re.compile(value)
except re.error:
raise ValidationError(
_('"%(value)s" is not a valid regular expression'),
params={'value': value}
)