summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorJacob Kaplan-Moss <jacob@jacobian.org>2006-11-07 04:29:07 +0000
committerJacob Kaplan-Moss <jacob@jacobian.org>2006-11-07 04:29:07 +0000
commit3a0733e12c2b0a03f80ff828f49f2cf6a258c138 (patch)
tree7d5736778ce42f8c20b7a2918864c7aa7e4a5c5d /django
parent4cb22473278df29c998a75fb1646dc821c75e0cc (diff)
Fixed #2364: added NumberIsInRange validator. Thanks, Matt McClanahan.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4039 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django')
-rw-r--r--django/core/validators.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/django/core/validators.py b/django/core/validators.py
index 816b8af8a3..a2f3dc3bc3 100644
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -353,6 +353,38 @@ class UniqueAmongstFieldsWithPrefix(object):
if field_name != self.field_name and value == field_data:
raise ValidationError, self.error_message
+class NumberIsInRange(object):
+ """
+ Validator that tests if a value is in a range (inclusive).
+ """
+ def __init__(self, lower=None, upper=None, error_message=''):
+ self.lower, self.upper = lower, upper
+ if not error_message:
+ if lower and upper:
+ self.error_message = gettext("This value must be between %s and %s.") % (lower, upper)
+ elif lower:
+ self.error_message = gettext("This value must be at least %s.") % lower
+ elif upper:
+ self.error_message = gettext("This value must be no more than %s.") % upper
+ else:
+ self.error_message = error_message
+
+ def __call__(self, field_data, all_data):
+ # Try to make the value numeric. If this fails, we assume another
+ # validator will catch the problem.
+ try:
+ val = float(field_data)
+ except ValueError:
+ return
+
+ # Now validate
+ if self.lower and self.upper and (val < self.lower or val > self.upper):
+ raise ValidationError(self.error_message)
+ elif self.lower and val < self.lower:
+ raise ValidationError(self.error_message)
+ elif self.upper and val > self.upper:
+ raise ValidationError(self.error_message)
+
class IsAPowerOf(object):
"""
>>> v = IsAPowerOf(2)