Reputation: 8020
I have been trying to use the new validators that are now included with Django. I have set the validators parameter on my fields and while I don't get an error, the validation doesn't seem to be working. Here is my console session that dupplicates the issue.
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import django >>> django.VERSION (1, 2, 1, 'final', 0) >>> from django.core import validators >>> from django import forms >>> field = forms.CharField(validators=[validators.MinValueValidator(2)]) >>> field.clean("s") u's'
I would expect the field.clean("s")
to throw a validation exception since there is only one character in the string. I realize it is possible that I am misunderstanding how to use the validators, so any help would be greatly appreciated.
Upvotes: 4
Views: 1788
Reputation: 309019
I think you want to try the MinLengthValidator
instead of the MinValueValidator
.
The MinValueValidator
checks that the field value is greater or equal to the given value.
>>> 's' > 2
True
Since "s" > 2
, no validation error is raised.
It would make more sense to use the MinValueError
with an IntegerField
or FloatField
.
>>> field = forms.FloatField(validators=[validators.MinValueValidator(2)])
>>> field.clean(5)
5.0
>>> field.clean(1.9)
...
ValidationError: [u'Ensure this value is greater than or equal to 2.']
To ensure that a string has a certain length, use the MinLengthValidator
.
>>> field = forms.CharField(validators=[validators.MinLengthValidator(2)])
>>> field.clean('abc')
u'abc'
>>> field.clean('s')
...
ValidationError: [u'Ensure this value has at least 2 characters (it has 1).']
Upvotes: 6