validators.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 reusing 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. from django.utils.translation import gettext_lazy as _
  15. def validate_even(value):
  16. if value % 2 != 0:
  17. raise ValidationError(
  18. _("%(value)s is not an even number"),
  19. params={"value": value},
  20. )
  21. You can add this to a model field via the field's :attr:`~django.db.models.Field.validators`
  22. argument::
  23. from django.db import models
  24. class MyModel(models.Model):
  25. even_field = models.IntegerField(validators=[validate_even])
  26. Because values are converted to Python before validators are run, you can even
  27. use the same validator with forms::
  28. from django import forms
  29. class MyForm(forms.Form):
  30. even_field = forms.IntegerField(validators=[validate_even])
  31. You can also use a class with a ``__call__()`` method for more complex or
  32. configurable validators. :class:`RegexValidator`, for example, uses this
  33. technique. If a class-based validator is used in the
  34. :attr:`~django.db.models.Field.validators` model field option, you should make
  35. sure it is :ref:`serializable by the migration framework
  36. <migration-serializing>` by adding :ref:`deconstruct()
  37. <custom-deconstruct-method>` and ``__eq__()`` methods.
  38. How validators are run
  39. ======================
  40. See the :doc:`form validation </ref/forms/validation>` for more information on
  41. how validators are run in forms, and :ref:`Validating objects
  42. <validating-objects>` for how they're run in models. Note that validators will
  43. not be run automatically when you save a model, but if you are using a
  44. :class:`~django.forms.ModelForm`, it will run your validators on any fields
  45. that are included in your form. See the
  46. :doc:`ModelForm documentation </topics/forms/modelforms>` for information on
  47. how model validation interacts with forms.
  48. Built-in validators
  49. ===================
  50. The :mod:`django.core.validators` module contains a collection of callable
  51. validators for use with model and form fields. They're used internally but
  52. are available for use with your own fields, too. They can be used in addition
  53. to, or in lieu of custom ``field.clean()`` methods.
  54. ``RegexValidator``
  55. ------------------
  56. .. class:: RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)
  57. :param regex: If not ``None``, overrides :attr:`regex`. Can be a regular
  58. expression string or a pre-compiled regular expression.
  59. :param message: If not ``None``, overrides :attr:`.message`.
  60. :param code: If not ``None``, overrides :attr:`code`.
  61. :param inverse_match: If not ``None``, overrides :attr:`inverse_match`.
  62. :param flags: If not ``None``, overrides :attr:`flags`. In that case,
  63. :attr:`regex` must be a regular expression string, or
  64. :exc:`TypeError` is raised.
  65. A :class:`RegexValidator` searches the provided ``value`` for a given
  66. regular expression with :func:`re.search`. By default, raises a
  67. :exc:`~django.core.exceptions.ValidationError` with :attr:`message` and
  68. :attr:`code` if a match **is not** found. Its behavior can be inverted by
  69. setting :attr:`inverse_match` to ``True``, in which case the
  70. :exc:`~django.core.exceptions.ValidationError` is raised when a match
  71. **is** found.
  72. .. attribute:: regex
  73. The regular expression pattern to search for within the provided
  74. ``value``, using :func:`re.search`. This may be a string or a
  75. pre-compiled regular expression created with :func:`re.compile`.
  76. Defaults to the empty string, which will be found in every possible
  77. ``value``.
  78. .. attribute:: message
  79. The error message used by
  80. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  81. Defaults to ``"Enter a valid value"``.
  82. .. attribute:: code
  83. The error code used by :exc:`~django.core.exceptions.ValidationError`
  84. if validation fails. Defaults to ``"invalid"``.
  85. .. attribute:: inverse_match
  86. The match mode for :attr:`regex`. Defaults to ``False``.
  87. .. attribute:: flags
  88. The :ref:`regex flags <python:contents-of-module-re>` used when
  89. compiling the regular expression string :attr:`regex`. If :attr:`regex`
  90. is a pre-compiled regular expression, and :attr:`flags` is overridden,
  91. :exc:`TypeError` is raised. Defaults to ``0``.
  92. ``EmailValidator``
  93. ------------------
  94. .. class:: EmailValidator(message=None, code=None, allowlist=None)
  95. :param message: If not ``None``, overrides :attr:`.message`.
  96. :param code: If not ``None``, overrides :attr:`code`.
  97. :param allowlist: If not ``None``, overrides :attr:`allowlist`.
  98. An :class:`EmailValidator` ensures that a value looks like an email, and
  99. raises a :exc:`~django.core.exceptions.ValidationError` with
  100. :attr:`message` and :attr:`code` if it doesn't. Values longer than 320
  101. characters are always considered invalid.
  102. .. attribute:: message
  103. The error message used by
  104. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  105. Defaults to ``"Enter a valid email address"``.
  106. .. attribute:: code
  107. The error code used by :exc:`~django.core.exceptions.ValidationError`
  108. if validation fails. Defaults to ``"invalid"``.
  109. .. attribute:: allowlist
  110. Allowlist of email domains. By default, a regular expression (the
  111. ``domain_regex`` attribute) is used to validate whatever appears after
  112. the ``@`` sign. However, if that string appears in the ``allowlist``,
  113. this validation is bypassed. If not provided, the default ``allowlist``
  114. is ``['localhost']``. Other domains that don't contain a dot won't pass
  115. validation, so you'd need to add them to the ``allowlist`` as
  116. necessary.
  117. ``DomainNameValidator``
  118. -----------------------
  119. .. class:: DomainNameValidator(accept_idna=True, message=None, code=None)
  120. A :class:`RegexValidator` subclass that ensures a value looks like a domain
  121. name. Values longer than 255 characters are always considered invalid. IP
  122. addresses are not accepted as valid domain names.
  123. In addition to the optional arguments of its parent :class:`RegexValidator`
  124. class, ``DomainNameValidator`` accepts an extra optional attribute:
  125. .. attribute:: accept_idna
  126. Determines whether to accept internationalized domain names, that is,
  127. domain names that contain non-ASCII characters. Defaults to ``True``.
  128. ``URLValidator``
  129. ----------------
  130. .. class:: URLValidator(schemes=None, regex=None, message=None, code=None)
  131. A :class:`RegexValidator` subclass that ensures a value looks like a URL,
  132. and raises an error code of ``'invalid'`` if it doesn't. Values longer than
  133. :attr:`max_length` characters are always considered invalid.
  134. Loopback addresses and reserved IP spaces are considered valid. Literal
  135. IPv6 addresses (:rfc:`3986#section-3.2.2`) and Unicode domains are both
  136. supported.
  137. In addition to the optional arguments of its parent :class:`RegexValidator`
  138. class, ``URLValidator`` accepts an extra optional attribute:
  139. .. attribute:: schemes
  140. URL/URI scheme list to validate against. If not provided, the default
  141. list is ``['http', 'https', 'ftp', 'ftps']``. As a reference, the IANA
  142. website provides a full list of `valid URI schemes`_.
  143. .. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  144. .. warning::
  145. Values starting with ``file:///`` will not pass validation even
  146. when the ``file`` scheme is provided. Valid values must contain a
  147. host.
  148. .. attribute:: max_length
  149. The maximum length of values that could be considered valid. Defaults
  150. to 2048 characters.
  151. ``validate_email``
  152. ------------------
  153. .. data:: validate_email
  154. An :class:`EmailValidator` instance without any customizations.
  155. ``validate_domain_name``
  156. ------------------------
  157. .. data:: validate_domain_name
  158. A :class:`DomainNameValidator` instance without any customizations.
  159. ``validate_slug``
  160. -----------------
  161. .. data:: validate_slug
  162. A :class:`RegexValidator` instance that ensures a value consists of only
  163. letters, numbers, underscores or hyphens.
  164. ``validate_unicode_slug``
  165. -------------------------
  166. .. data:: validate_unicode_slug
  167. A :class:`RegexValidator` instance that ensures a value consists of only
  168. Unicode letters, numbers, underscores, or hyphens.
  169. ``validate_ipv4_address``
  170. -------------------------
  171. .. data:: validate_ipv4_address
  172. A :class:`RegexValidator` instance that ensures a value looks like an IPv4
  173. address.
  174. ``validate_ipv6_address``
  175. -------------------------
  176. .. data:: validate_ipv6_address
  177. Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.
  178. ``validate_ipv46_address``
  179. --------------------------
  180. .. data:: validate_ipv46_address
  181. Uses both ``validate_ipv4_address`` and ``validate_ipv6_address`` to
  182. ensure a value is either a valid IPv4 or IPv6 address.
  183. ``validate_comma_separated_integer_list``
  184. -----------------------------------------
  185. .. data:: validate_comma_separated_integer_list
  186. A :class:`RegexValidator` instance that ensures a value is a
  187. comma-separated list of integers.
  188. ``int_list_validator``
  189. ----------------------
  190. .. function:: int_list_validator(sep=',', message=None, code='invalid', allow_negative=False)
  191. Returns a :class:`RegexValidator` instance that ensures a string consists
  192. of integers separated by ``sep``. It allows negative integers when
  193. ``allow_negative`` is ``True``.
  194. ``MaxValueValidator``
  195. ---------------------
  196. .. class:: MaxValueValidator(limit_value, message=None)
  197. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  198. ``'max_value'`` if ``value`` is greater than ``limit_value``, which may be
  199. a callable.
  200. ``MinValueValidator``
  201. ---------------------
  202. .. class:: MinValueValidator(limit_value, message=None)
  203. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  204. ``'min_value'`` if ``value`` is less than ``limit_value``, which may be a
  205. callable.
  206. ``MaxLengthValidator``
  207. ----------------------
  208. .. class:: MaxLengthValidator(limit_value, message=None)
  209. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  210. ``'max_length'`` if the length of ``value`` is greater than
  211. ``limit_value``, which may be a callable.
  212. ``MinLengthValidator``
  213. ----------------------
  214. .. class:: MinLengthValidator(limit_value, message=None)
  215. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  216. ``'min_length'`` if the length of ``value`` is less than ``limit_value``,
  217. which may be a callable.
  218. ``DecimalValidator``
  219. --------------------
  220. .. class:: DecimalValidator(max_digits, decimal_places)
  221. Raises :exc:`~django.core.exceptions.ValidationError` with the following
  222. codes:
  223. - ``'max_digits'`` if the number of digits is larger than ``max_digits``.
  224. - ``'max_decimal_places'`` if the number of decimals is larger than
  225. ``decimal_places``.
  226. - ``'max_whole_digits'`` if the number of whole digits is larger than
  227. the difference between ``max_digits`` and ``decimal_places``.
  228. ``FileExtensionValidator``
  229. --------------------------
  230. .. class:: FileExtensionValidator(allowed_extensions, message, code)
  231. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  232. ``'invalid_extension'`` if the extension of ``value.name`` (``value`` is
  233. a :class:`~django.core.files.File`) isn't found in ``allowed_extensions``.
  234. The extension is compared case-insensitively with ``allowed_extensions``.
  235. .. warning::
  236. Don't rely on validation of the file extension to determine a file's
  237. type. Files can be renamed to have any extension no matter what data
  238. they contain.
  239. ``validate_image_file_extension``
  240. ---------------------------------
  241. .. data:: validate_image_file_extension
  242. Uses Pillow to ensure that ``value.name`` (``value`` is a
  243. :class:`~django.core.files.File`) has `a valid image extension
  244. <https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html>`_.
  245. ``ProhibitNullCharactersValidator``
  246. -----------------------------------
  247. .. class:: ProhibitNullCharactersValidator(message=None, code=None)
  248. Raises a :exc:`~django.core.exceptions.ValidationError` if ``str(value)``
  249. contains one or more null characters (``'\x00'``).
  250. :param message: If not ``None``, overrides :attr:`.message`.
  251. :param code: If not ``None``, overrides :attr:`code`.
  252. .. attribute:: message
  253. The error message used by
  254. :exc:`~django.core.exceptions.ValidationError` if validation fails.
  255. Defaults to ``"Null characters are not allowed."``.
  256. .. attribute:: code
  257. The error code used by :exc:`~django.core.exceptions.ValidationError`
  258. if validation fails. Defaults to ``"null_characters_not_allowed"``.
  259. ``StepValueValidator``
  260. ----------------------
  261. .. class:: StepValueValidator(limit_value, message=None, offset=None)
  262. Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
  263. ``'step_size'`` if ``value`` is not an integral multiple of
  264. ``limit_value``, which can be a float, integer or decimal value or a
  265. callable. When ``offset`` is set, the validation occurs against
  266. ``limit_value`` plus ``offset``. For example, for
  267. ``StepValueValidator(3, offset=1.4)`` valid values include ``1.4``,
  268. ``4.4``, ``7.4``, ``10.4``, and so on.