validators.txt 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. ==========
  2. Validators
  3. ==========
  4. .. module:: django.core.validators
  5. :synopsis: Validation utilities and base classes
  6. Writing validators
  7. ==================
  8. A validator is a callable that takes a value and raises a
  9. :exc:`~django.core.exceptions.ValidationError` if it doesn't meet some
  10. criteria. Validators can be useful for re-using validation logic between
  11. different types of fields.
  12. For example, here's a validator that only allows even numbers::
  13. from django.core.exceptions import ValidationError
  14. def validate_even(value):
  15. if value % 2 != 0:
  16. raise ValidationError('%s is not an even number' % value)
  17. You can add this to a model field via the field's :attr:`~django.db.models.Field.validators`
  18. argument::
  19. from django.db import models
  20. class MyModel(models.Model):
  21. even_field = models.IntegerField(validators=[validate_even])
  22. Because values are converted to Python before validators are run, you can even
  23. use the same validator with forms::
  24. from django import forms
  25. class MyForm(forms.Form):
  26. even_field = forms.IntegerField(validators=[validate_even])
  27. How validators are run
  28. ======================
  29. See the :doc:`form validation </ref/forms/validation>` for more information on
  30. how validators are run in forms, and :ref:`Validating objects
  31. <validating-objects>` for how they're run in models. Note that validators will
  32. not be run automatically when you save a model, but if you are using a
  33. :class:`~django.forms.ModelForm`, it will run your validators on any fields
  34. that are included in your form. See the
  35. :doc:`ModelForm documentation </topics/forms/modelforms>` for information on
  36. how model validation interacts with forms.
  37. Built-in validators
  38. ===================
  39. The :mod:`django.core.validators` module contains a collection of callable
  40. validators for use with model and form fields. They're used internally but
  41. are available for use with your own fields, too. They can be used in addition
  42. to, or in lieu of custom ``field.clean()`` methods.
  43. ``RegexValidator``
  44. ------------------
  45. .. class:: RegexValidator([regex=None, message=None, code=None, inverse_match=None, flags=0])
  46. :param regex: If not ``None``, overrides :attr:`regex`. Can be a regular
  47. expression string or a pre-compiled regular expression.
  48. :param message: If not ``None``, overrides :attr:`.message`.
  49. :param code: If not ``None``, overrides :attr:`code`.
  50. :param inverse_match: If not ``None``, overrides :attr:`inverse_match`.
  51. :param flags: If not ``None``, overrides :attr:`flags`. In that case,
  52. :attr:`regex` must be a regular expression string, or
  53. :exc:`~exceptions.TypeError` is raised.
  54. .. attribute:: regex
  55. The regular expression pattern to search for the provided ``value``,
  56. or a pre-compiled regular expression. Raises a
  57. :exc:`~django.core.exceptions.ValidationError` with :attr:`message`
  58. and :attr:`code` if :attr:`inverse_match` is ``False`` and a match is
  59. found, or if :attr:`inverse_match` is ``True`` and a match is not found.
  60. By default, matches any string (including an empty string).
  61. .. attribute:: message
  62. The error message used by
  63. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  64. Defaults to ``"Enter a valid value"``.
  65. .. attribute:: code
  66. The error code used by :exc:`~django.core.exceptions.ValidationError`
  67. if validation fails. Defaults to ``"invalid"``.
  68. .. attribute:: inverse_match
  69. .. versionadded:: 1.7
  70. The match mode for :attr:`regex`. Defaults to ``False``.
  71. .. attribute:: flags
  72. .. versionadded:: 1.7
  73. The flags used when compiling the regular expression string :attr:`regex`.
  74. If :attr:`regex` is a pre-compiled regular expression, and :attr:`flags` is overridden,
  75. :exc:`~exceptions.TypeError` is raised.
  76. Defaults to `0`.
  77. ``URLValidator``
  78. ----------------
  79. .. class:: URLValidator([schemes=None, regex=None, message=None, code=None])
  80. A :class:`RegexValidator` that ensures a value looks like a URL, and raises
  81. an error code of ``'invalid'`` if it doesn't. In addition to the optional
  82. arguments of its parent :class:`RegexValidator` class, ``URLValidator``
  83. accepts an extra optional attribute:
  84. .. attribute:: schemes
  85. URL/URI scheme list to validate against. If not provided, the default
  86. list is ``['http', 'https', 'ftp', 'ftps']``. As a reference, the IANA
  87. Web site provides a full list of `valid URI schemes`_.
  88. .. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  89. .. versionchanged:: 1.7
  90. The optional ``schemes`` attribute was added.
  91. ``validate_email``
  92. ------------------
  93. .. data:: validate_email
  94. An ``EmailValidator`` instance that ensures a value looks like an
  95. email address.
  96. ``validate_slug``
  97. -----------------
  98. .. data:: validate_slug
  99. A :class:`RegexValidator` instance that ensures a value consists of only
  100. letters, numbers, underscores or hyphens.
  101. ``validate_ipv4_address``
  102. -------------------------
  103. .. data:: validate_ipv4_address
  104. A :class:`RegexValidator` instance that ensures a value looks like an IPv4
  105. address.
  106. ``validate_ipv6_address``
  107. -------------------------
  108. .. data:: validate_ipv6_address
  109. Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.
  110. ``validate_ipv46_address``
  111. --------------------------
  112. .. data:: validate_ipv46_address
  113. Uses both ``validate_ipv4_address`` and ``validate_ipv6_address`` to
  114. ensure a value is either a valid IPv4 or IPv6 address.
  115. ``validate_comma_separated_integer_list``
  116. -----------------------------------------
  117. .. data:: validate_comma_separated_integer_list
  118. A :class:`RegexValidator` instance that ensures a value is a
  119. comma-separated list of integers.
  120. ``MaxValueValidator``
  121. ---------------------
  122. .. class:: MaxValueValidator(max_value)
  123. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  124. ``'max_value'`` if ``value`` is greater than ``max_value``.
  125. ``MinValueValidator``
  126. ---------------------
  127. .. class:: MinValueValidator(min_value)
  128. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  129. ``'min_value'`` if ``value`` is less than ``min_value``.
  130. ``MaxLengthValidator``
  131. ----------------------
  132. .. class:: MaxLengthValidator(max_length)
  133. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  134. ``'max_length'`` if the length of ``value`` is greater than ``max_length``.
  135. ``MinLengthValidator``
  136. ----------------------
  137. .. class:: MinLengthValidator(min_length)
  138. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  139. ``'min_length'`` if the length of ``value`` is less than ``min_length``.