Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixed #17125 -- Made it possible to change a `RegexField`'s regular e…

…xpression validator after it has been initialized. Thanks to Claude Paroz for the report and patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17076 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 90d369741727dbf0cf1c94b23fb2340c7edb8b02 1 parent b745fc0
@jphalip jphalip authored
View
15 django/forms/fields.py
@@ -442,10 +442,21 @@ def __init__(self, regex, max_length=None, min_length=None, error_message=None,
error_messages['invalid'] = error_message
kwargs['error_messages'] = error_messages
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
+ self._set_regex(regex)
+
+ def _get_regex(self):
+ return self._regex
+
+ def _set_regex(self, regex):
if isinstance(regex, basestring):
regex = re.compile(regex)
- self.regex = regex
- self.validators.append(validators.RegexValidator(regex=regex))
+ self._regex = regex
+ if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
+ self.validators.remove(self._regex_validator)
+ self._regex_validator = validators.RegexValidator(regex=regex)
+ self.validators.append(self._regex_validator)
+
+ regex = property(_get_regex, _set_regex)
class EmailField(CharField):
default_error_messages = {
View
6 tests/regressiontests/forms/tests/fields.py
@@ -493,6 +493,12 @@ def test_regexfield_5(self):
self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901')
self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a')
+ def test_change_regex_after_init(self):
+ f = RegexField('^[a-z]+$')
+ f.regex = '^\d+$'
+ self.assertEqual(u'1234', f.clean('1234'))
+ self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, 'abcd')
+
# EmailField ##################################################################
def test_emailfield_1(self):
Please sign in to comment.
Something went wrong with that request. Please try again.