validators.txt 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. You can also use a class with a ``__call__()`` method for more complex or
  28. configurable validators. :class:`RegexValidator`, for example, uses this
  29. technique. If a class-based validator is used in the
  30. :attr:`~django.db.models.Field.validators` model field option, you should make
  31. sure it is :ref:`serializable by the migration framework
  32. <migration-serializing>` by adding :ref:`deconstruct()
  33. <custom-deconstruct-method>` and ``__eq__()`` methods.
  34. How validators are run
  35. ======================
  36. See the :doc:`form validation </ref/forms/validation>` for more information on
  37. how validators are run in forms, and :ref:`Validating objects
  38. <validating-objects>` for how they're run in models. Note that validators will
  39. not be run automatically when you save a model, but if you are using a
  40. :class:`~django.forms.ModelForm`, it will run your validators on any fields
  41. that are included in your form. See the
  42. :doc:`ModelForm documentation </topics/forms/modelforms>` for information on
  43. how model validation interacts with forms.
  44. Built-in validators
  45. ===================
  46. The :mod:`django.core.validators` module contains a collection of callable
  47. validators for use with model and form fields. They're used internally but
  48. are available for use with your own fields, too. They can be used in addition
  49. to, or in lieu of custom ``field.clean()`` methods.
  50. ``RegexValidator``
  51. ------------------
  52. .. class:: RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)
  53. :param regex: If not ``None``, overrides :attr:`regex`. Can be a regular
  54. expression string or a pre-compiled regular expression.
  55. :param message: If not ``None``, overrides :attr:`.message`.
  56. :param code: If not ``None``, overrides :attr:`code`.
  57. :param inverse_match: If not ``None``, overrides :attr:`inverse_match`.
  58. :param flags: If not ``None``, overrides :attr:`flags`. In that case,
  59. :attr:`regex` must be a regular expression string, or
  60. :exc:`TypeError` is raised.
  61. .. attribute:: regex
  62. The regular expression pattern to search for the provided ``value``,
  63. or a pre-compiled regular expression. By default, raises a
  64. :exc:`~django.core.exceptions.ValidationError` with :attr:`message`
  65. and :attr:`code` if a match is not found. That standard behavior can
  66. be reversed by setting :attr:`inverse_match` to ``True``, in which case
  67. the :exc:`~django.core.exceptions.ValidationError` is raised when a
  68. match **is** found. By default, matches any string (including an empty
  69. string).
  70. .. attribute:: message
  71. The error message used by
  72. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  73. Defaults to ``"Enter a valid value"``.
  74. .. attribute:: code
  75. The error code used by :exc:`~django.core.exceptions.ValidationError`
  76. if validation fails. Defaults to ``"invalid"``.
  77. .. attribute:: inverse_match
  78. The match mode for :attr:`regex`. Defaults to ``False``.
  79. .. attribute:: flags
  80. The flags used when compiling the regular expression string
  81. :attr:`regex`. If :attr:`regex` is a pre-compiled regular expression,
  82. and :attr:`flags` is overridden, :exc:`TypeError` is raised. Defaults
  83. to ``0``.
  84. ``EmailValidator``
  85. ------------------
  86. .. class:: EmailValidator(message=None, code=None, whitelist=None)
  87. :param message: If not ``None``, overrides :attr:`.message`.
  88. :param code: If not ``None``, overrides :attr:`code`.
  89. :param whitelist: If not ``None``, overrides :attr:`whitelist`.
  90. .. attribute:: message
  91. The error message used by
  92. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  93. Defaults to ``"Enter a valid email address"``.
  94. .. attribute:: code
  95. The error code used by :exc:`~django.core.exceptions.ValidationError`
  96. if validation fails. Defaults to ``"invalid"``.
  97. .. attribute:: whitelist
  98. Whitelist of email domains to allow. By default, a regular expression
  99. (the ``domain_regex`` attribute) is used to validate whatever appears
  100. after the @ sign. However, if that string appears in the whitelist, this
  101. validation is bypassed. If not provided, the default whitelist is
  102. ``['localhost']``. Other domains that don't contain a dot won't pass
  103. validation, so you'd need to whitelist them as necessary.
  104. ``URLValidator``
  105. ----------------
  106. .. class:: URLValidator(schemes=None, regex=None, message=None, code=None)
  107. A :class:`RegexValidator` that ensures a value looks like a URL, and raises
  108. an error code of ``'invalid'`` if it doesn't.
  109. Loopback addresses and reserved IP spaces are considered valid. Literal
  110. IPv6 addresses (:rfc:`2732`) and unicode domains are both supported.
  111. In addition to the optional arguments of its parent :class:`RegexValidator`
  112. class, ``URLValidator`` accepts an extra optional attribute:
  113. .. attribute:: schemes
  114. URL/URI scheme list to validate against. If not provided, the default
  115. list is ``['http', 'https', 'ftp', 'ftps']``. As a reference, the IANA
  116. website provides a full list of `valid URI schemes`_.
  117. .. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  118. ``validate_email``
  119. ------------------
  120. .. data:: validate_email
  121. An :class:`EmailValidator` instance without any customizations.
  122. ``validate_slug``
  123. -----------------
  124. .. data:: validate_slug
  125. A :class:`RegexValidator` instance that ensures a value consists of only
  126. letters, numbers, underscores or hyphens.
  127. ``validate_unicode_slug``
  128. -------------------------
  129. .. data:: validate_unicode_slug
  130. .. versionadded:: 1.9
  131. A :class:`RegexValidator` instance that ensures a value consists of only
  132. Unicode letters, numbers, underscores, or hyphens.
  133. ``validate_ipv4_address``
  134. -------------------------
  135. .. data:: validate_ipv4_address
  136. A :class:`RegexValidator` instance that ensures a value looks like an IPv4
  137. address.
  138. ``validate_ipv6_address``
  139. -------------------------
  140. .. data:: validate_ipv6_address
  141. Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.
  142. ``validate_ipv46_address``
  143. --------------------------
  144. .. data:: validate_ipv46_address
  145. Uses both ``validate_ipv4_address`` and ``validate_ipv6_address`` to
  146. ensure a value is either a valid IPv4 or IPv6 address.
  147. ``validate_comma_separated_integer_list``
  148. -----------------------------------------
  149. .. data:: validate_comma_separated_integer_list
  150. A :class:`RegexValidator` instance that ensures a value is a
  151. comma-separated list of integers.
  152. ``int_list_validator``
  153. ----------------------
  154. .. function:: int_list_validator(sep=',', message=None, code='invalid')
  155. .. versionadded:: 1.9
  156. Returns a :class:`RegexValidator` instance that ensures a string
  157. consists of integers separated by ``sep``.
  158. ``MaxValueValidator``
  159. ---------------------
  160. .. class:: MaxValueValidator(max_value, message=None)
  161. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  162. ``'max_value'`` if ``value`` is greater than ``max_value``.
  163. ``MinValueValidator``
  164. ---------------------
  165. .. class:: MinValueValidator(min_value, message=None)
  166. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  167. ``'min_value'`` if ``value`` is less than ``min_value``.
  168. ``MaxLengthValidator``
  169. ----------------------
  170. .. class:: MaxLengthValidator(max_length, message=None)
  171. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  172. ``'max_length'`` if the length of ``value`` is greater than ``max_length``.
  173. ``MinLengthValidator``
  174. ----------------------
  175. .. class:: MinLengthValidator(min_length, message=None)
  176. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  177. ``'min_length'`` if the length of ``value`` is less than ``min_length``.
  178. ``DecimalValidator``
  179. --------------------
  180. .. class:: DecimalValidator(max_digits, decimal_places)
  181. .. versionadded:: 1.9
  182. Raises :exc:`~django.core.exceptions.ValidationError` with the following
  183. codes:
  184. - ``'max_digits'`` if the number of digits is larger than ``max_digits``.
  185. - ``'max_decimal_places'`` if the number of decimals is larger than
  186. ``decimal_places``.
  187. - ``'max_whole_digits'`` if the number of whole digits is larger than
  188. the difference between ``max_digits`` and ``decimal_places``.