Validator Reference

Core Date/Time Numbers File-related Internet-related
dict date numeric bytesIO email
json datetime integer stringIO url
string time float path domain
iterable timezone fraction path_exists ip_address
none timedelta decimal file_exists ipv4
not_empty     directory_exists ipv6
uuid     readable mac_address
variable_name     writeable mimetype
      executable  

Using Validators

A validator does what it says on the tin: It validates that an input value is what you think it should be, and returns its valid form.

Each validator is expressed as the name of the thing being validated, for example email().

Each validator accepts a value as its first argument, and an optional allow_empty boolean as its second argument. For example:

email_address = validators.email(value, allow_empty = True)

If the value you’re validating validates successfully, it will be returned. If the value you’re validating needs to be coerced to a different type, the validator will try to do that. So for example:

validators.integer(1)
validators.integer('1')

will both return an int of 1.

If the value you’re validating is empty/falsey and allow_empty is False, then the validator will raise a EmptyValueError exception (which inherits from the built-in ValueError). If allow_empty is True, then an empty/falsey input value will be converted to a None value.

Caution

By default, allow_empty is always set to False.

Hint

Some validators (particularly numeric ones like integer) have additional options which are used to make sure the value meets criteria that you set for it. These options are always included as keyword arguments after the allow_empty argument, and are documented for each validator below.

When Validation Fails

Validators raise exceptions when validation fails. All exceptions raised inherit from built-in exceptions like ValueError, TypeError, and IOError.

If the value you’re validating fails its validation for some reason, the validator may raise different exceptions depending on the reason. In most cases, this will be a descendent of ValueError though it can sometimes be a TypeError, or an IOError, etc.

For specifics on each validator’s likely exceptions and what can cause them, please review the Validator Reference.

Hint

While validators will always raise built-in exceptions from the standard library, to give you greater programmatic control over how to respond when validation fails, we have defined a set of custom exceptions that inherit from those built-ins.

Our custom exceptions provide you with very specific, fine-grained information as to why validation for a given value failed. In general, most validators will raise ValueError or TypeError exceptions, and you can safely catch those and be fine. But if you want to handle specific types of situations with greater control, then you can instead catch EmptyValueError, CannotCoerceError, MaximumValueError, and the like.

For more detailed information, please see: Error Reference and Validator Reference.

Disabling Validation

Caution

If you are disabling validators using the VALIDATORS_DISABLED environment variable, their related checkers will also be disabled (meaning they will always return True).

Validation can at times be an expensive (in terms of performance) operation. As a result, there are times when you want to disable certain kinds of validation when running in production. Using the Validator-Collection this is simple:

Just add the name of the validator you want disabled to the VALIDATORS_DISABLED environment variable, and validation will automatically be skipped.

Caution

VALIDATORS_DISABLED expects a comma-separated list of values. If it isn’t comma-separated, it won’t work properly.

Here’s how it works in practice. Let’s say we define the following environment variable:

$ export VALIDATORS_DISABLED = "variable_name, email, ipv4"

This disables the variable_name(), email(), and ipv4() validators respectively.

Now if we run:

from validator_collection import validators, errors

try:
    result = validators.variable_name('this is an invalid variable name')
except ValueError:
    # handle the error

The validator will return the value supplied to it un-changed. So that means result will be equal to this is an invalid variable name.

However, if we run:

from validator_collection import validators, errors

try:
    result = validators.integer('this is an invalid variable name')
except errors.NotAnIntegerError:
    # handle the error

the validator will run and raise NotAnIntegerError.

We can force validators to run (even if disabled using the environment variable) by passing a force_run = True keyword argument. For example:

from validator_collection import validators, errors

try:
    result = validators.variable_name('this is an invalid variable name',
                                      force_run = True)
except ValueError:
    # handle the error

will produce a InvalidVariableNameError (which is a type of ValueError).


Core

dict

dict(value, allow_empty=False, json_serializer=None, **kwargs)[source]

Validate that value is a dict.

Hint

If value is a string, this validator will assume it is a JSON object and try to convert it into a dict

You can override the JSON serializer used by passing it to the json_serializer property. By default, will utilize the Python json encoder/decoder.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • json_serializer (callable) – The JSON encoder/decoder to use to deserialize a string passed in value. If not supplied, will default to the Python json encoder/decoder.
Returns:

value / None

Return type:

dict / None

Raises:

json

json(value, schema=None, allow_empty=False, json_serializer=None, **kwargs)[source]

Validate that value conforms to the supplied JSON Schema.

Note

schema supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a $schema property, the schema will be assumed to conform to Draft 7.

Hint

If either value or schema is a string, this validator will assume it is a JSON object and try to convert it into a dict.

You can override the JSON serializer used by passing it to the json_serializer property. By default, will utilize the Python json encoder/decoder.

Parameters:
  • value – The value to validate.
  • schema – An optional JSON Schema against which value will be validated.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • json_serializer (callable) – The JSON encoder/decoder to use to deserialize a string passed in value. If not supplied, will default to the Python json encoder/decoder.
Returns:

value / None

Return type:

dict / list of dict / None

Raises:

string

string(value, allow_empty=False, coerce_value=False, minimum_length=None, maximum_length=None, whitespace_padding=False, **kwargs)[source]

Validate that value is a valid string.

Parameters:
  • value (str / None) – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • coerce_value (bool) – If True, will attempt to coerce value to a string if it is not already. If False, will raise a ValueError if value is not a string. Defaults to False.
  • minimum_length (int) – If supplied, indicates the minimum number of characters needed to be valid.
  • maximum_length (int) – If supplied, indicates the minimum number of characters needed to be valid.
  • whitespace_padding (bool) – If True and the value is below the minimum_length, pad the value with spaces. Defaults to False.
Returns:

value / None

Return type:

str / None

Raises:
  • EmptyValueError – if value is empty and allow_empty is False
  • CannotCoerceError – if value is not a valid string and coerce_value is False
  • MinimumLengthError – if minimum_length is supplied and the length of value is less than minimum_length and whitespace_padding is False
  • MaximumLengthError – if maximum_length is supplied and the length of value is more than the maximum_length

iterable

iterable(value, allow_empty=False, forbid_literals=(<class 'str'>, <class 'bytes'>), minimum_length=None, maximum_length=None, **kwargs)[source]

Validate that value is a valid iterable.

Hint

This validator checks to ensure that value supports iteration using any of Python’s three iteration protocols: the __getitem__ protocol, the __iter__ / next() protocol, or the inheritance from Python’s Iterable abstract base class.

If value supports any of these three iteration protocols, it will be validated. However, if iteration across value raises an unsupported exception, this function will raise an IterationFailedError

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • forbid_literals (iterable) – A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to str and bytes.
  • minimum_length (int) – If supplied, indicates the minimum number of members needed to be valid.
  • maximum_length (int) – If supplied, indicates the minimum number of members needed to be valid.
Returns:

value / None

Return type:

iterable / None

Raises:
  • EmptyValueError – if value is empty and allow_empty is False
  • NotAnIterableError – if value is not a valid iterable or None
  • IterationFailedError – if value is a valid iterable, but iteration fails for some unexpected exception
  • MinimumLengthError – if minimum_length is supplied and the length of value is less than minimum_length and whitespace_padding is False
  • MaximumLengthError – if maximum_length is supplied and the length of value is more than the maximum_length

none

none(value, allow_empty=False, **kwargs)[source]

Validate that value is None.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty but not None. If False, raises a NotNoneError if value is empty but not None. Defaults to False.
Returns:

None

Raises:

NotNoneError – if allow_empty is False and value is empty but not None and

not_empty

not_empty(value, allow_empty=False, **kwargs)[source]

Validate that value is not empty.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
Returns:

value / None

Raises:

EmptyValueError – if value is empty and allow_empty is False

uuid

uuid(value, allow_empty=False, **kwargs)[source]

Validate that value is a valid UUID.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
Returns:

value coerced to a UUID object / None

Return type:

UUID / None

Raises:

variable_name

variable_name(value, allow_empty=False, **kwargs)[source]

Validate that the value is a valid Python variable name.

Caution

This function does NOT check whether the variable exists. It only checks that the value would work as a Python variable (or class, or function, etc.) name.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
Returns:

value / None

Return type:

str or None

Raises:

EmptyValueError – if allow_empty is False and value is empty


Date / Time

date

date(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]

Validate that value is a valid date.

Parameters:
  • value (str / datetime / date / None) – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • minimum (datetime / date / compliant str / None) – If supplied, will make sure that value is on or after this value.
  • maximum (datetime / date / compliant str / None) – If supplied, will make sure that value is on or before this value.
  • coerce_value (bool) – If True, will attempt to coerce value to a date if it is a timestamp value. If False, will not.
Returns:

value / None

Return type:

date / None

Raises:

datetime

datetime(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]

Validate that value is a valid datetime.

Caution

If supplying a string, the string needs to be in an ISO 8601-format to pass validation. If it is not in an ISO 8601-format, validation will fail.

Parameters:
  • value (str / datetime / date / None) – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • minimum (datetime / date / compliant str / None) – If supplied, will make sure that value is on or after this value.
  • maximum (datetime / date / compliant str / None) – If supplied, will make sure that value is on or before this value.
  • coerce_value (bool) – If True, will coerce dates to datetime objects with times of 00:00:00. If False, will error if value is not an unambiguous timestamp. Defaults to True.
Returns:

value / None

Return type:

datetime / None

Raises:

time

time(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]

Validate that value is a valid time.

Caution

This validator will always return the time as timezone naive (effectively UTC). If value has a timezone / UTC offset applied, the validator will coerce the value returned back to UTC.

Parameters:
  • value (datetime or time-compliant str / datetime / time) – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • minimum (datetime or time-compliant str / datetime / time) – If supplied, will make sure that value is on or after this value.
  • maximum (datetime or time-compliant str / datetime / time) – If supplied, will make sure that value is on or before this value.
  • coerce_value (bool) – If True, will attempt to coerce/extract a time from value. If False, will only respect direct representations of time. Defaults to True.
Returns:

value in UTC time / None

Return type:

time / None

Raises:

timezone

timezone(value, allow_empty=False, positive=True, **kwargs)[source]

Validate that value is a valid tzinfo.

Caution

This does not verify whether the value is a timezone that actually exists, nor can it resolve timezone names (e.g. 'Eastern' or 'CET').

For that kind of functionality, we recommend you utilize: pytz

Parameters:
  • value (str / tzinfo / numeric / None) – The value to validate.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • positive (bool) – Indicates whether the value is positive or negative (only has meaning if value is a string). Defaults to True.
Returns:

value / None

Return type:

tzinfo / None

Raises:

timedelta

timedelta(value, allow_empty=False, resolution='seconds', **kwargs)[source]

Validate that value is a valid timedelta.

Note

Expects to receive a value that is either a timedelta, a numeric value that can be coerced to a timedelta, or a string that can be coerced to a timedelta. Coerceable string formats are:

  • HH:MM:SS
  • X day, HH:MM:SS
  • X days, HH:MM:SS
  • HH:MM:SS.us
  • X day, HH:MM:SS.us
  • X days, HH:MM:SS.us

where “us” refer to microseconds. Shout out to Alex Pitchford for sharing the string-parsing regex.

Parameters:
  • value (str / timedelta / numeric / None) – The value to validate. Accepts either a numeric value indicating a number of seconds or a string indicating an amount of time.
  • allow_empty (bool) – If True, returns None if value is empty. If False, raises a EmptyValueError if value is empty. Defaults to False.
  • resolution (str) – Indicates the time period resolution represented by value. Accepts 'years', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', or 'microseconds'. Defaults to 'seconds'.
Returns:

value / None

Return type:

timedelta / None

Raises:

Numbers

Note

Because Python’s None is implemented as an integer value, numeric validators do not check “falsiness”. Doing so would find false positives if value were set to 0.

Instead, all numeric validators explicitly check for the Python global singleton None.

numeric

numeric(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]

Validate that value is a numeric value.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is None. If False, raises an EmptyValueError if value is None. Defaults to False.
  • minimum (numeric) – If supplied, will make sure that value is greater than or equal to this value.
  • maximum (numeric) – If supplied, will make sure that value is less than or equal to this value.
Returns:

value / None

Raises:

integer

integer(value, allow_empty=False, coerce_value=False, minimum=None, maximum=None, base=10, **kwargs)[source]

Validate that value is an int.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is None. If False, raises a EmptyValueError if value is None. Defaults to False.
  • coerce_value (bool) – If True, will force any numeric value to an integer (always rounding up). If False, will raise an error if value is numeric but not a whole number. Defaults to False.
  • minimum (numeric) – If supplied, will make sure that value is greater than or equal to this value.
  • maximum (numeric) – If supplied, will make sure that value is less than or equal to this value.
  • base – Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to 10.
Returns:

value / None

Raises:

float

float(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]

Validate that value is a float.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is None. If False, raises a EmptyValueError if value is None. Defaults to False.
Returns:

value / None

Return type:

float / None

Raises:

fraction

fraction(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]

Validate that value is a Fraction.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is None. If False, raises a EmptyValueError if value is None. Defaults to False.
Returns:

value / None

Return type:

Fraction / None

Raises:

decimal

decimal(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]

Validate that value is a Decimal.

Parameters:
  • value – The value to validate.
  • allow_empty (bool) – If True, returns None if value is None. If False, raises a EmptyValueError if value is None. Defaults to False.
  • minimum (numeric) – If supplied, will make sure that value is greater than or equal to this value.
  • maximum (numeric) – If supplied, will make sure that value is less than or equal to this value.
Returns:

value / None

Return type:

Decimal / None

Raises: