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 theVALIDATORS_DISABLEDenvironment 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
valueis adict.Hint
If
valueis a string, this validator will assume it is a JSON object and try to convert it into adictYou can override the JSON serializer used by passing it to the
json_serializerproperty. By default, will utilize the Pythonjsonencoder/decoder.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis 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 Pythonjsonencoder/decoder.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced to adict - NotADictError – if
valueis not adict
json¶
-
json(value, schema=None, allow_empty=False, json_serializer=None, **kwargs)[source]¶ Validate that
valueconforms to the supplied JSON Schema.Note
schemasupports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a$schemaproperty, the schema will be assumed to conform to Draft 7.Hint
If either
valueorschemais 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_serializerproperty. By default, will utilize the Pythonjsonencoder/decoder.Parameters: - value – The value to validate.
- schema – An optional JSON Schema against which
valuewill be validated. - allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis 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 Pythonjsonencoder/decoder.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced to adict - NotJSONError – if
valuecannot be deserialized from JSON - NotJSONSchemaError – if
schemais not a valid JSON Schema object - JSONValidationError – if
valuedoes 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
valueis a valid string.Parameters: - value (
str/None) – The value to validate. - allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - coerce_value (
bool) – IfTrue, will attempt to coercevalueto a string if it is not already. IfFalse, will raise aValueErrorifvalueis 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) – IfTrueand the value is below theminimum_length, pad the value with spaces. Defaults toFalse.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valueis not a valid string andcoerce_valueisFalse - MinimumLengthError – if
minimum_lengthis supplied and the length ofvalueis less thanminimum_lengthandwhitespace_paddingisFalse - MaximumLengthError – if
maximum_lengthis supplied and the length ofvalueis 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
valueis a valid iterable.Hint
This validator checks to ensure that
valuesupports 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
valuesupports any of these three iteration protocols, it will be validated. However, if iteration acrossvalueraises an unsupported exception, this function will raise anIterationFailedErrorParameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - forbid_literals (iterable) – A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to
strandbytes. - 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/NoneReturn type: iterable /
NoneRaises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - NotAnIterableError – if
valueis not a valid iterable orNone - IterationFailedError – if
valueis a valid iterable, but iteration fails for some unexpected exception - MinimumLengthError – if
minimum_lengthis supplied and the length ofvalueis less thanminimum_lengthandwhitespace_paddingisFalse - MaximumLengthError – if
maximum_lengthis supplied and the length ofvalueis more than themaximum_length
none¶
-
none(value, allow_empty=False, **kwargs)[source]¶ Validate that
valueisNone.Parameters: Returns: Raises: NotNoneError – if
allow_emptyisFalseandvalueis empty but notNoneand
not_empty¶
-
not_empty(value, allow_empty=False, **kwargs)[source]¶ Validate that
valueis not empty.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse.
Returns: value/NoneRaises: EmptyValueError – if
valueis empty andallow_emptyisFalse
uuid¶
-
uuid(value, allow_empty=False, **kwargs)[source]¶ Validate that
valueis a validUUID.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse.
Returns: Return type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot 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
valuewould work as a Python variable (or class, or function, etc.) name.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse.
Returns: value/NoneReturn type: Raises: EmptyValueError – if
allow_emptyisFalseandvalueis empty
Date / Time¶
date¶
-
date(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]¶ Validate that
valueis a valid date.Parameters: - value (
str/datetime/date/None) – The value to validate. - allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - minimum (
datetime/date/ compliantstr/None) – If supplied, will make sure thatvalueis on or after this value. - maximum (
datetime/date/ compliantstr/None) – If supplied, will make sure thatvalueis on or before this value. - coerce_value (
bool) – IfTrue, will attempt to coercevalueto adateif it is a timestamp value. IfFalse, will not.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced to adateand is notNone - MinimumValueError – if
minimumis supplied butvalueoccurs beforeminimum - MaximumValueError – if
maximumis supplied butvalueoccurs aftermaximum
- value (
datetime¶
-
datetime(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]¶ Validate that
valueis 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, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - minimum (
datetime/date/ compliantstr/None) – If supplied, will make sure thatvalueis on or after this value. - maximum (
datetime/date/ compliantstr/None) – If supplied, will make sure thatvalueis on or before this value. - coerce_value (
bool) – IfTrue, will coerce dates todatetimeobjects with times of 00:00:00. IfFalse, will error ifvalueis not an unambiguous timestamp. Defaults toTrue.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced to adatetimevalue and is notNone - MinimumValueError – if
minimumis supplied butvalueoccurs beforeminimum - MaximumValueError – if
maximumis supplied butvalueoccurs afterminimum
- value (
time¶
-
time(value, allow_empty=False, minimum=None, maximum=None, coerce_value=True, **kwargs)[source]¶ Validate that
valueis a validtime.Caution
This validator will always return the time as timezone naive (effectively UTC). If
valuehas a timezone / UTC offset applied, the validator will coerce the value returned back to UTC.Parameters: - value (
datetimeortime-compliantstr/datetime/time) – The value to validate. - allow_empty (
bool) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - minimum (
datetimeortime-compliantstr/datetime/time) – If supplied, will make sure thatvalueis on or after this value. - maximum (
datetimeortime-compliantstr/datetime/time) – If supplied, will make sure thatvalueis on or before this value. - coerce_value (
bool) – IfTrue, will attempt to coerce/extract atimefromvalue. IfFalse, will only respect direct representations of time. Defaults toTrue.
Returns: valuein UTC time /NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced to atimeand is notNone - MinimumValueError – if
minimumis supplied butvalueoccurs beforeminimum - MaximumValueError – if
maximumis supplied butvalueoccurs afterminimum
- value (
timezone¶
-
timezone(value, allow_empty=False, positive=True, **kwargs)[source]¶ Validate that
valueis 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, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - positive (
bool) – Indicates whether thevalueis positive or negative (only has meaning ifvalueis a string). Defaults toTrue.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced totzinfoand is notNone - PositiveOffsetMismatchError – if
positiveisTrue, but the offset indicated byvalueis actually negative - NegativeOffsetMismatchError – if
positiveisFalse, but the offset indicated byvalueis actually positive
- value (
timedelta¶
-
timedelta(value, allow_empty=False, resolution='seconds', **kwargs)[source]¶ Validate that
valueis a validtimedelta.Note
Expects to receive a value that is either a
timedelta, a numeric value that can be coerced to atimedelta, or a string that can be coerced to atimedelta. 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) – IfTrue, returnsNoneifvalueis empty. IfFalse, raises aEmptyValueErrorifvalueis empty. Defaults toFalse. - resolution (
str) – Indicates the time period resolution represented byvalue. Accepts'years','weeks','days','hours','minutes','seconds','milliseconds', or'microseconds'. Defaults to'seconds'.
Returns: value/NoneReturn type: Raises: - ValueError – if
resolutionis not a valid time period resolution - EmptyValueError – if
valueis empty andallow_emptyisFalse - CannotCoerceError – if
valuecannot be coerced totimedeltaand is notNone
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
valueis a numeric value.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueisNone. IfFalse, raises anEmptyValueErrorifvalueisNone. Defaults toFalse. - minimum (numeric) – If supplied, will make sure that
valueis greater than or equal to this value. - maximum (numeric) – If supplied, will make sure that
valueis less than or equal to this value.
Returns: value/NoneRaises: - EmptyValueError – if
valueisNoneandallow_emptyisFalse - MinimumValueError – if
minimumis supplied andvalueis less than theminimum - MaximumValueError – if
maximumis supplied andvalueis more than themaximum - CannotCoerceError – if
valuecannot 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
valueis anint.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueisNone. IfFalse, raises aEmptyValueErrorifvalueisNone. Defaults toFalse. - coerce_value (
bool) – IfTrue, will force any numericvalueto an integer (always rounding up). IfFalse, will raise an error ifvalueis numeric but not a whole number. Defaults toFalse. - minimum (numeric) – If supplied, will make sure that
valueis greater than or equal to this value. - maximum (numeric) – If supplied, will make sure that
valueis 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/NoneRaises: - EmptyValueError – if
valueisNoneandallow_emptyisFalse - MinimumValueError – if
minimumis supplied andvalueis less than theminimum - MaximumValueError – if
maximumis supplied andvalueis more than themaximum - NotAnIntegerError – if
coerce_valueisFalse, andvalueis not an integer - CannotCoerceError – if
valuecannot be coerced to anint
float¶
-
float(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
valueis afloat.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueisNone. IfFalse, raises aEmptyValueErrorifvalueisNone. Defaults toFalse.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueisNoneandallow_emptyisFalse - MinimumValueError – if
minimumis supplied andvalueis less than theminimum - MaximumValueError – if
maximumis supplied andvalueis more than themaximum - CannotCoerceError – if unable to coerce
valueto afloat
fraction¶
-
fraction(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
valueis aFraction.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueisNone. IfFalse, raises aEmptyValueErrorifvalueisNone. Defaults toFalse.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueisNoneandallow_emptyisFalse - MinimumValueError – if
minimumis supplied andvalueis less than theminimum - MaximumValueError – if
maximumis supplied andvalueis more than themaximum - CannotCoerceError – if unable to coerce
valueto aFraction
decimal¶
-
decimal(value, allow_empty=False, minimum=None, maximum=None, **kwargs)[source]¶ Validate that
valueis aDecimal.Parameters: - value – The value to validate.
- allow_empty (
bool) – IfTrue, returnsNoneifvalueisNone. IfFalse, raises aEmptyValueErrorifvalueisNone. Defaults toFalse. - minimum (numeric) – If supplied, will make sure that
valueis greater than or equal to this value. - maximum (numeric) – If supplied, will make sure that
valueis less than or equal to this value.
Returns: value/NoneReturn type: Raises: - EmptyValueError – if
valueisNoneandallow_emptyisFalse - MinimumValueError – if
minimumis supplied andvalueis less than theminimum - MaximumValueError – if
maximumis supplied andvalueis more than themaximum - CannotCoerceError – if unable to coerce
valueto aDecimal