Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #2364: added NumberIsInRange validator. Thanks, Matt McClanahan.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4039 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 3a0733e12c2b0a03f80ff828f49f2cf6a258c138 1 parent 4cb2247
Jacob Kaplan-Moss jacobian authored
Showing with 41 additions and 0 deletions.
  1. +32 −0 django/core/validators.py
  2. +9 −0 docs/forms.txt
32 django/core/validators.py
View
@@ -353,6 +353,38 @@ def __call__(self, field_data, all_data):
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)
9 docs/forms.txt
View
@@ -610,6 +610,15 @@ fails. If no message is passed in, a default message is used.
string "123" is less than the string "2", for example. If you don't want
string comparison here, you will need to write your own validator.
+``NumberIsInRange``
+ Takes two boundary number, ``lower`` and ``upper`` and checks that the
+ field is greater than ``lower`` (if given) and less than ``upper`` (if
+ given).
+
+ Both checks are inclusive; that is, ``NumberIsInRange(10, 20)`` will allow
+ values of both 10 and 20. This validator only checks numeric fields
+ (i.e. floats and integer fields).
+
``IsAPowerOf``
Takes an integer argument and when called as a validator, checks that the
field being validated is a power of the integer.
Please sign in to comment.
Something went wrong with that request. Please try again.