Opened 32 hours ago

Closed 31 hours ago

#36019 closed Bug (duplicate)

MinValueValidator and MaxValueValidator messages do not match compare operators

Reported by: Samuel Nussbaumer Owned by:
Component: Core (Other) Version: 5.1
Severity: Normal Keywords:
Cc: Samuel Nussbaumer Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: yes

Description

Excerpt from /django/core/validators.py:

@deconstructible
class MaxValueValidator(BaseValidator):
    message = _("Ensure this value is **less than or equal** to %(limit_value)s.")
    code = "max_value"

    def compare(self, a, b):
        return a > b


@deconstructible
class MinValueValidator(BaseValidator):
    message = _("Ensure this value is **greater than or equal** to %(limit_value)s.")
    code = "min_value"

    def compare(self, a, b):
        return a < b

The messages imply that the comparison between a and b would be a <= b or a >= b whereas in practice they only check if a is greater or lesser than b.

Reprod:

  1. Define a form field with validators=[MaxValueValidator(3), MinValueValidator(0.2)]
  2. On the form, type in 0.2 and save -> ValidationError: Ensure this value is greater than or equal to 0.2.

Expected behavior: The form should not raise any ValidationErrors (according to the error message)

Change History (2)

comment:1 by Samuel Nussbaumer, 32 hours ago

Cc: Samuel Nussbaumer added

comment:2 by Sarah Boyce, 31 hours ago

Resolution: duplicate
Status: newclosed

This appears to be a duplicate of #32037

The logic is correct. I guess this is what is causing confusion

>>> from decimal import Decimal
>>> Decimal("0.2") < 0.2
True

And so...

>>> from django.core.validators import MaxValueValidator, MinValueValidator
>>> from django import forms
>>> field = forms.DecimalField(validators=[MaxValueValidator(3.0), MinValueValidator(Decimal("0.2"))])
>>> field.clean(Decimal("0.2"))
Decimal('0.2')
>>> field = forms.DecimalField(validators=[MaxValueValidator(3.0), MinValueValidator(0.2)])
>>> field.clean(Decimal("0.2"))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/path_to_venv/lib/python3.10/site-packages/django/forms/fields.py", line 206, in clean
    self.run_validators(value)
  File "/path_to_venv/site-packages/django/forms/fields.py", line 197, in run_validators
    raise ValidationError(errors)
django.core.exceptions.ValidationError: ['Ensure this value is greater than or equal to 0.2.']
Note: See TracTickets for help on using tickets.
Back to Top