Debian Codegraph @

docs/ref/validators.txt

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