From 7e57576ff7fcad814c7a86de12d933a219106f8f Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Sat, 8 Sep 2007 19:24:46 +0000 Subject: [PATCH] Fixed #5232 -- Fixed the validation of `DecimalField` so that the negative sign is not counted as a digit. Thanks, Andrew Durdin. git-svn-id: http://code.djangoproject.com/svn/django/trunk@6067 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/validators.py | 2 +- django/newforms/fields.py | 2 +- tests/regressiontests/forms/tests.py | 25 +++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/django/core/validators.py b/django/core/validators.py index 8a93462b21..5ef00fbff4 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -423,7 +423,7 @@ class IsValidDecimal(object): except DecimalException: raise ValidationError, _("Please enter a valid decimal number.") - pieces = str(val).split('.') + pieces = str(val).lstrip("-").split('.') decimals = (len(pieces) == 2) and len(pieces[1]) or 0 digits = len(pieces[0]) diff --git a/django/newforms/fields.py b/django/newforms/fields.py index bb8a3dc582..cce07fa8bb 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -190,7 +190,7 @@ class DecimalField(Field): value = Decimal(value) except DecimalException: raise ValidationError(ugettext('Enter a number.')) - pieces = str(value).split('.') + pieces = str(value).lstrip("-").split('.') decimals = (len(pieces) == 2) and len(pieces[1]) or 0 digits = len(pieces[0]) if self.max_value is not None and value > self.max_value: diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/tests.py index 78442677eb..0df3ee3858 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/tests.py @@ -1167,6 +1167,31 @@ ValidationError: [u'Ensure that there are no more than 2 decimal places.'] Traceback (most recent call last): ... ValidationError: [u'Ensure that there are no more than 2 digits before the decimal point.'] +>>> f.clean('-12.34') +Decimal("-12.34") +>>> f.clean('-123.45') +Traceback (most recent call last): +... +ValidationError: [u'Ensure that there are no more than 4 digits in total.'] +>>> f.clean('-.12') +Decimal("-0.12") +>>> f.clean('-00.12') +Decimal("-0.12") +>>> f.clean('-000.12') +Decimal("-0.12") +>>> f.clean('-000.123') +Traceback (most recent call last): +... +ValidationError: [u'Ensure that there are no more than 2 decimal places.'] +>>> f.clean('-000.1234') +Traceback (most recent call last): +... +ValidationError: [u'Ensure that there are no more than 4 digits in total.'] +>>> f.clean('--0.12') +Traceback (most recent call last): +... +ValidationError: [u'Enter a number.'] + >>> f = DecimalField(max_digits=4, decimal_places=2, required=False) >>> f.clean('')