Commit 14a459b1 authored by Valentin Samir's avatar Valentin Samir

Add a validator to models CharField that should be regular expressions

parent 282e3a83
......@@ -466,7 +466,8 @@ class ServicePattern(models.Model):
"A regular expression matching services. "
"Will usually looks like '^https://some\\.server\\.com/path/.*$'."
"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
user_field = models.CharField(
......@@ -660,7 +661,8 @@ class FilterAttributValue(models.Model):
pattern = models.CharField(
max_length=255,
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
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.filters`
......@@ -689,7 +691,8 @@ class ReplaceAttributValue(models.Model):
pattern = models.CharField(
max_length=255,
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 …
replace = models.CharField(
......
......@@ -255,3 +255,9 @@ class UtilsTestCase(TestCase):
self.assertIsInstance(result, dict)
self.assertIn('applied', result)
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("[")
......@@ -18,7 +18,10 @@ from django.contrib import messages
from django.contrib.messages import constants as DEFAULT_MESSAGE_LEVELS
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import re
import random
import string
import json
......@@ -700,3 +703,19 @@ def logout_request(ticket):
'datetime': timezone.now().isoformat(),
'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}
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment