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 |
decimal |
file_exists |
ipv4 |
|
not_empty |
directory_exists |
ipv6 |
||
uuid |
readable |
mac_address |
||
variable_name |
writeable |
|||
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 theVALIDATORS_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 adict
.Hint
If
value
is a string, this validator will assume it is a JSON object and try to convert it into adict
You can override the JSON serializer used by passing it to the
json_serializer
property. By default, will utilize the Pythonjson
encoder/decoder.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - json_serializer (callable) – The JSON encoder/decoder to use to deserialize a
string passed in
value
. If not supplied, will default to the Pythonjson
encoder/decoder.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to adict
- NotADictError – if
value
is not adict
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
orschema
is a string, this validator will assume it is a JSON object and try to convert it into adict
.You can override the JSON serializer used by passing it to the
json_serializer
property. By default, will utilize the Pythonjson
encoder/decoder.Parameters: - value – The value to validate.
- schema – An optional JSON Schema against which
value
will be validated. - allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - json_serializer (callable) – The JSON encoder/decoder to use to deserialize a
string passed in
value
. If not supplied, will default to the Pythonjson
encoder/decoder.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to adict
- NotJSONError – if
value
cannot be deserialized from JSON - NotJSONSchemaError – if
schema
is not a valid JSON Schema object - JSONValidationError – if
value
does not validate against the JSON Schema
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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - coerce_value (
bool
) – IfTrue
, will attempt to coercevalue
to a string if it is not already. IfFalse
, will raise aValueError
ifvalue
is not a string. Defaults toFalse
. - 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
) – IfTrue
and the value is below theminimum_length
, pad the value with spaces. Defaults toFalse
.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
is not a valid string andcoerce_value
isFalse
- MinimumLengthError – if
minimum_length
is supplied and the length ofvalue
is less thanminimum_length
andwhitespace_padding
isFalse
- MaximumLengthError – if
maximum_length
is supplied and the length ofvalue
is more than themaximum_length
- value (
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.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - forbid_literals (iterable) – A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to
str
andbytes
. - 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 andallow_empty
isFalse
- NotAnIterableError – if
value
is not a valid iterable orNone
- MinimumLengthError – if
minimum_length
is supplied and the length ofvalue
is less thanminimum_length
andwhitespace_padding
isFalse
- MaximumLengthError – if
maximum_length
is supplied and the length ofvalue
is more than themaximum_length
none¶
-
none
(value, allow_empty=False, **kwargs)[source]¶ Validate that
value
isNone
.Parameters: Returns: Raises: NotNoneError – if
allow_empty
isFalse
andvalue
is empty but notNone
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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
.
Returns: value
/None
Raises: EmptyValueError – if
value
is empty andallow_empty
isFalse
uuid¶
-
uuid
(value, allow_empty=False, **kwargs)[source]¶ Validate that
value
is a validUUID
.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
.
Returns: Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to aUUID
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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
.
Returns: value
/None
Return type: Raises: EmptyValueError – if
allow_empty
isFalse
andvalue
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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - minimum (
datetime
/date
/ compliantstr
/None
) – If supplied, will make sure thatvalue
is on or after this value. - maximum (
datetime
/date
/ compliantstr
/None
) – If supplied, will make sure thatvalue
is on or before this value. - coerce_value (
bool
) – IfTrue
, will attempt to coercevalue
to adate
if it is a timestamp value. IfFalse
, will not.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to adate
and is notNone
- MinimumValueError – if
minimum
is supplied butvalue
occurs beforeminimum
- MaximumValueError – if
maximum
is supplied butvalue
occurs aftermaximum
- value (
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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - minimum (
datetime
/date
/ compliantstr
/None
) – If supplied, will make sure thatvalue
is on or after this value. - maximum (
datetime
/date
/ compliantstr
/None
) – If supplied, will make sure thatvalue
is on or before this value. - coerce_value (
bool
) – IfTrue
, will coerce dates todatetime
objects with times of 00:00:00. IfFalse
, will error ifvalue
is not an unambiguous timestamp. Defaults toTrue
.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to adatetime
value and is notNone
- MinimumValueError – if
minimum
is supplied butvalue
occurs beforeminimum
- MaximumValueError – if
maximum
is supplied butvalue
occurs afterminimum
- value (
time¶
-
time
(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]¶ Validate that
value
is a validtime
.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
ortime
-compliantstr
/datetime
/time
) – The value to validate. - allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - minimum (
datetime
ortime
-compliantstr
/datetime
/time
) – If supplied, will make sure thatvalue
is on or after this value. - maximum (
datetime
ortime
-compliantstr
/datetime
/time
) – If supplied, will make sure thatvalue
is on or before this value. - coerce_value (
bool
) – IfTrue
, will attempt to coerce/extract atime
fromvalue
. IfFalse
, will only respect direct representations of time. Defaults toTrue
.
Returns: value
in UTC time /None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced to atime
and is notNone
- MinimumValueError – if
minimum
is supplied butvalue
occurs beforeminimum
- MaximumValueError – if
maximum
is supplied butvalue
occurs afterminimum
- value (
timezone¶
-
timezone
(value, allow_empty=False, positive=True, **kwargs)[source]¶ Validate that
value
is a validtzinfo
.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
) – IfTrue
, returnsNone
ifvalue
is empty. IfFalse
, raises aEmptyValueError
ifvalue
is empty. Defaults toFalse
. - positive (
bool
) – Indicates whether thevalue
is positive or negative (only has meaning ifvalue
is a string). Defaults toTrue
.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
is empty andallow_empty
isFalse
- CannotCoerceError – if
value
cannot be coerced totzinfo
and is notNone
- PositiveOffsetMismatchError – if
positive
isTrue
, but the offset indicated byvalue
is actually negative - NegativeOffsetMismatchError – if
positive
isFalse
, but the offset indicated byvalue
is actually positive
- value (
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
) – IfTrue
, returnsNone
ifvalue
isNone
. IfFalse
, raises anEmptyValueError
ifvalue
isNone
. Defaults toFalse
. - 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: - EmptyValueError – if
value
isNone
andallow_empty
isFalse
- MinimumValueError – if
minimum
is supplied andvalue
is less than theminimum
- MaximumValueError – if
maximum
is supplied andvalue
is more than themaximum
- CannotCoerceError – if
value
cannot be coerced to a numeric form
integer¶
-
integer
(value, allow_empty=False, coerce_value=False, minimum=None, maximum=None, base=10, **kwargs)[source]¶ Validate that
value
is anint
.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
isNone
. IfFalse
, raises aEmptyValueError
ifvalue
isNone
. Defaults toFalse
. - coerce_value (
bool
) – IfTrue
, will force any numericvalue
to an integer (always rounding up). IfFalse
, will raise an error ifvalue
is numeric but not a whole number. Defaults toFalse
. - 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
, or0x/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 to10
.
Returns: value
/None
Raises: - EmptyValueError – if
value
isNone
andallow_empty
isFalse
- MinimumValueError – if
minimum
is supplied andvalue
is less than theminimum
- MaximumValueError – if
maximum
is supplied andvalue
is more than themaximum
- NotAnIntegerError – if
coerce_value
isFalse
, andvalue
is not an integer - CannotCoerceError – if
value
cannot be coerced to anint
float¶
-
float
(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
value
is afloat
.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
isNone
. IfFalse
, raises aEmptyValueError
ifvalue
isNone
. Defaults toFalse
.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
isNone
andallow_empty
isFalse
- MinimumValueError – if
minimum
is supplied andvalue
is less than theminimum
- MaximumValueError – if
maximum
is supplied andvalue
is more than themaximum
- CannotCoerceError – if unable to coerce
value
to afloat
fraction¶
-
fraction
(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
value
is aFraction
.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
isNone
. IfFalse
, raises aEmptyValueError
ifvalue
isNone
. Defaults toFalse
.
Returns: value
/None
Return type: Raises: - EmptyValueError – if
value
isNone
andallow_empty
isFalse
- MinimumValueError – if
minimum
is supplied andvalue
is less than theminimum
- MaximumValueError – if
maximum
is supplied andvalue
is more than themaximum
- CannotCoerceError – if unable to coerce
value
to aFraction
decimal¶
-
decimal
(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
value
is aDecimal
.Parameters: - value – The value to validate.
- allow_empty (
bool
) – IfTrue
, returnsNone
ifvalue
isNone
. IfFalse
, raises aEmptyValueError
ifvalue
isNone
. Defaults toFalse
. - 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: Raises: - EmptyValueError – if
value
isNone
andallow_empty
isFalse
- MinimumValueError – if
minimum
is supplied andvalue
is less than theminimum
- MaximumValueError – if
maximum
is supplied andvalue
is more than themaximum
- CannotCoerceError – if unable to coerce
value
to aDecimal