Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[soc2009/model-validation] Make validators work with error messages c…

…ontaining paramters.

Implemented MaxValueValidator and MinValueValidator and migrated number
based form.Fields to use those instead of hardwired code. The validators
themselves are likely to change.

Covered by existing tests

git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@11186 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit d23f541f102bc37e5ed9e78a05832335f3f3987b 1 parent 63f244f
Honza Král authored July 05, 2009
3  django/core/exceptions.py
@@ -35,7 +35,7 @@ class FieldError(Exception):
35 35
 NON_FIELD_ERRORS = '__all__'
36 36
 class ValidationError(Exception):
37 37
     """An error while validating data."""
38  
-    def __init__(self, message, code=None):
  38
+    def __init__(self, message, code=None, params=None):
39 39
         import operator
40 40
         from django.utils.encoding import force_unicode
41 41
         """
@@ -50,6 +50,7 @@ def __init__(self, message, code=None):
50 50
             self.messages = [force_unicode(msg) for msg in message]
51 51
         else:
52 52
             self.code = code
  53
+            self.params = params
53 54
             message = force_unicode(message)
54 55
             self.messages = [message]
55 56
 
23  django/core/validators.py
@@ -22,6 +22,29 @@ def validate_email(value):
22 22
     if not email_re.search(smart_unicode(value)):
23 23
         raise ValidationError(_(u'Enter a valid e-mail address.'), code='invalid')
24 24
 
  25
+class MaxValueValidator(object):
  26
+    def __init__(self, max_value):
  27
+        self.max_value = max_value
  28
+
  29
+    def __call__(self, value):
  30
+        if value > self.max_value:
  31
+            raise ValidationError(
  32
+                _(u'Ensure this value is less than or equal to %s.') % self.max_value,
  33
+                code='max_value',
  34
+                params=(self.max_value,)
  35
+            )
  36
+class MinValueValidator(object):
  37
+    def __init__(self, min_value):
  38
+        self.min_value = min_value
  39
+
  40
+    def __call__(self, value):
  41
+        if value < self.min_value:
  42
+            raise ValidationError(
  43
+                _(u'Ensure this value is greater than or equal to %s.') % self.min_value,
  44
+                code='min_value',
  45
+                params=(self.min_value,)
  46
+            )
  47
+
25 48
 class ComplexValidator(object):
26 49
     def get_value(self, name, all_values, obj):
27 50
         assert all_values or obj, "Either all_values or obj must be supplied"
30  django/forms/fields.py
@@ -128,7 +128,10 @@ def run_validators(self, value):
128 128
                     v(value)
129 129
                 except ValidationError, e:
130 130
                     if hasattr(e, 'code'):
131  
-                        errors.append(self.error_messages.get(e.code, e.messages[0]))
  131
+                        message = self.error_messages.get(e.code, e.messages[0])
  132
+                        if e.params:
  133
+                            message = message % e.params
  134
+                        errors.append(message)
132 135
                     else:
133 136
                         errors.extend(e.messages)
134 137
         if errors:
@@ -201,9 +204,13 @@ class IntegerField(Field):
201 204
     }
202 205
 
203 206
     def __init__(self, max_value=None, min_value=None, *args, **kwargs):
204  
-        self.max_value, self.min_value = max_value, min_value
205 207
         super(IntegerField, self).__init__(*args, **kwargs)
206 208
 
  209
+        if max_value is not None:
  210
+            self.validators.append(validators.MaxValueValidator(max_value))
  211
+        if min_value is not None:
  212
+            self.validators.append(validators.MinValueValidator(min_value))
  213
+
207 214
     def to_python(self, value):
208 215
         """
209 216
         Validates that int() can be called on the input. Returns the result
@@ -219,15 +226,6 @@ def to_python(self, value):
219 226
             raise ValidationError(self.error_messages['invalid'])
220 227
         return value
221 228
 
222  
-    def validate(self, value):
223  
-        super(IntegerField, self).validate(value)
224  
-        if value in validators.EMPTY_VALUES:
225  
-            return
226  
-        if self.max_value is not None and value > self.max_value:
227  
-            raise ValidationError(self.error_messages['max_value'] % self.max_value)
228  
-        if self.min_value is not None and value < self.min_value:
229  
-            raise ValidationError(self.error_messages['min_value'] % self.min_value)
230  
-
231 229
 class FloatField(IntegerField):
232 230
     default_error_messages = {
233 231
         'invalid': _(u'Enter a number.'),
@@ -261,10 +259,14 @@ class DecimalField(Field):
261 259
     }
262 260
 
263 261
     def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
264  
-        self.max_value, self.min_value = max_value, min_value
265 262
         self.max_digits, self.decimal_places = max_digits, decimal_places
266 263
         Field.__init__(self, *args, **kwargs)
267 264
 
  265
+        if max_value is not None:
  266
+            self.validators.append(validators.MaxValueValidator(max_value))
  267
+        if min_value is not None:
  268
+            self.validators.append(validators.MinValueValidator(min_value))
  269
+
268 270
     def to_python(self, value):
269 271
         """
270 272
         Validates that the input is a decimal number. Returns a Decimal
@@ -297,10 +299,6 @@ def validate(self, value):
297 299
             digits = decimals
298 300
         whole_digits = digits - decimals
299 301
 
300  
-        if self.max_value is not None and value > self.max_value:
301  
-            raise ValidationError(self.error_messages['max_value'] % self.max_value)
302  
-        if self.min_value is not None and value < self.min_value:
303  
-            raise ValidationError(self.error_messages['min_value'] % self.min_value)
304 302
         if self.max_digits is not None and digits > self.max_digits:
305 303
             raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
306 304
         if self.decimal_places is not None and decimals > self.decimal_places:

0 notes on commit d23f541

Please sign in to comment.
Something went wrong with that request. Please try again.