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