Reference¶
Core Validation Functions¶
Functions for validating simple, immutable, built-in data-types.
Numbers¶
-
validation.number.
validate_int
(value=<optional>, min_value=None, max_value=None, required=True)[source]¶ Checks that the target value is a valid integer, and that it fits in the requested bounds.
Does not accept integer values encoded as
floats
. Adding a value to afloat
will result in a loss of precision if the total is greater than2**53
. The division operator also behaves differently in python 2.Parameters: - value (int) – The number to be validated.
- min_value (int) – The minimum acceptable value for the number.
- max_value (int) – The maximum acceptable value for the number.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: - TypeError – If the value is not an integer, or if it was marked as required but None was passed in.
- ValueError – If the value is not within bounds.
-
validation.number.
validate_float
(value=<optional>, min_value=None, max_value=None, allow_infinite=False, allow_nan=False, required=True)[source]¶ Checks that the target value is a valid floating point number and that it fits in the requested bounds.
Parameters: - value (int) – The number to be validated.
- min_value (int) – The minimum acceptable value for the number.
- max_value (int) – The maximum acceptable value for the number.
- allow_infinite (bool) – Whether or not to accept positive or negative infinities. Defaults to
False
. - allow_nan (bool) – Whether or not to accept NaNs. Defaults to
False
. - required (bool) – Whether the value can be
None
. Defaults toTrue
.
Raises: - TypeError – If the value is not an integer, or if it was marked as
required
butNone
was passed in. - ValueError – If the value is not within bounds.
Strings¶
-
validation.string.
validate_text
(value=<optional>, min_length=None, max_length=None, pattern=None, required=True)[source]¶ Checks that the target value is a valid human readable string value.
In python 2 this will strictly enforce the use of
unicode
.str``s are not accepted as there is no way to tell if they are the result of decoding a byte-string containing only ``latin-1
characters or if they are still encoded. In python 3 things are much simpler.Patterns are python regular expressions and must match the entire string.
A simple example that uses the pattern parameter to validate a string describing a date:
def parse_date(string): validate_text(string, pattern='[0-9]{4}-[0-9]{2}-[0-9]{2}') # Do something ...
Parameters: - value (unicode) – The string to be validated.
- min_length (int) – The minimum length of the string.
- max_length (int) – The maximum acceptable length for the string. By default, the length is not checked.
- pattern (str|re.Pattern) – Regular expression to check the value against.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: - TypeError – If the value is not a unicode string , or if it was marked as required but None was passed in.
- ValueError – If the value was longer or shorter than expected, or did not match the pattern.
-
validation.string.
validate_bytes
(value=<optional>, min_length=None, max_length=None, required=True)[source]¶ Checks that the supplied value is a valid byte-string.
In python 3 will accepts bytes, in python 2 str.
Should not be used for validating human readable strings, Please use
validate_text()
instead.Parameters: - value (bytes) – The string to be validated.
- min_length (int) – The minimum length of the string.
- max_length (int) – The maximum acceptable length for the string. By default, the length is not checked.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: - TypeError – If the value is not a byte-string, or if it was marked as required but None was passed in.
- ValueError – If the value was longer or shorter than expected.
Time¶
-
validation.datetime.
validate_date
(value=<optional>, required=True)[source]¶ Checks that the value is a valid
datetime.date
value.Parameters: - value (datetime.date) – The value to be validated.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: TypeError – If the value is not a date, or if it was marked as required but None was passed in.
-
validation.datetime.
validate_datetime
(value=<optional>, required=True)[source]¶ Checks that the value is a valid
datetime.datetime
value.The value must have a valid timezone to be accepted. Naive datetime objects are not allowed.
Parameters: - value (datetime.date) – The value to be validated.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: - TypeError – If the value is not a datetime, or if it was marked as required but None was passed in.
- ValueError – If the value does not have a valid timezone.
Other¶
-
validation.core.
validate_bool
(value=<optional>, required=True)[source]¶ Checks that the target value is a valid boolean.
Parameters: - value – The value to be validated.
- required (bool) – Whether the value can be None. Defaults to True.
Raises: TypeError – If the value is not a boolean, or if it was marked as required but None was passed in.
Datastructure Validation Functions¶
This module contains functions for validating plain data-structures.
These functions typically expect to be passed another validator function for one or more of their arguments, that will be used to check every entry, key or value that that the data-structure contains. All validator functions in this library, when called with no value argument, will return a closure that is intended to be used in this context.
As an example, to check that a list contains only positive integers, you can
call validate_int()
with min_value
equal to zero
to create a closure that will check for positive integers, and pass it as the
validator
argument to validate_list()
.
>>> from validation import validate_int
>>> values = [3, 2, 1, -1]
>>> validate_list(values, validator=validate_int(min_value=0))
Traceback (most recent call last):
...
ValueError: invalid item at position 3: expected value less than 0, but got -1
Note that the exception raised here is not the exception that was raised by
validate_int()
.
For the subset of built-in exceptions that can be raised, in normal usage, by
validators in this library - namely TypeError
, ValueError
,
KeyError
, IndexError
and AssertionError
- we will attempt
to create and raise a copy of the original with additional context information
added to the message.
The other built-in exceptions don’t make sense as validation errors and so we
don’t try to catch them.
There doesn’t appear to be a safe way to extend custom exceptions so these are
also left alone.
There is no single validate_dict
function.
Dictionaries can be validated either as a mapping, that maps between keys of
one type and values of another, using validate_mapping()
, or as struct
like objects, that map predefined keys to values with key specific types, using
validate_structure()
.
The relationship between validate_list()
and validate_tuple()
is
similar. validate_list()
expects the list to be homogeneous, while
validate_tuple()
will check each entry with its own validation function.
Sequences¶
-
validation.datastructure.
validate_list
(value=<optional>, validator=None, min_length=None, max_length=None, required=True)[source]¶ Checks that the supplied value is a valid list.
Parameters: - value (list) – The array to be validated.
- validator (func) – A function to be called on each value in the list to check that it is valid.
- min_length (int) – The minimum acceptable length for the list. If None, the minimum length is not checked.
- max_length (int) – The maximum acceptable length for the list. If None, the maximum length is not checked.
- required (bool) – Whether the value can be None. Defaults to True.
-
validation.datastructure.
validate_set
(value=<optional>, validator=None, min_length=None, max_length=None, required=True)[source]¶ Validator to check a set and all entries in it.
Parameters: - value (set) – The set to be validated.
- validator (func) – A function to be called on each entry in the set to check that it is valid.
- min_length (int) – The minimum acceptable number of entries in the set. If None, the minimum size is not checked.
- max_length (int) – The maximum acceptable number of entries in the set. If None, the maximum size is not checked.
- required (bool) – Whether the value can be None. Defaults to True.
-
validation.datastructure.
validate_tuple
(value=<optional>, schema=None, length=None, required=True)[source]¶ Validates a tuple, checking it against an optional schema.
The schema should be a tuple of validator functions, with each validator corresponding to an entry in the value to be checked.
As an alternative, validate_tuple can accept a length argument. Unlike the validators for other sequence types, validate_tuple will always enforce an exact length. This is because the length of a tuple is part of its type.
A simple example:
validator = validate_tuple(schema=( validate_int(), validate_int(), validate_int(), )) validator((1, 2, 3))
Parameters: - value (tuple) – The value to be validated.
- schema (tuple) – An optional schema against which the value should be checked.
- length (int) – The maximum length of the tuple. schema and length arguments are mutually exclusive and must not be passed at the same time.
- required (bool) – Whether the value can’t be None. Defaults to True.
Dictionaries¶
-
validation.datastructure.
validate_mapping
(value=<optional>, key_validator=None, value_validator=None, required=True)[source]¶ Validates a dictionary representing a simple mapping from keys of one type to values of another.
For validating dictionaries representing structured data, where the keys are known ahead of time and values can have different constraints depending on the key, use
validate_struct()
.Parameters: - value (dict) – The value to be validated.
- key_validator (func) – Optional function to be call to check each of the keys in the dictionary.
- value_validator (func) – Optional function to be call to check each of the values in the dictionary.
- required (bool) – Whether the value can’t be None. Defaults to True.
-
validation.datastructure.
validate_structure
(value=<optional>, schema=None, allow_extra=False, required=True)[source]¶ Validates a structured dictionary, with value types depending on the key, checking it against an optional schema.
The schema should be a dictionary, with keys corresponding to the expected keys in value, but with the values replaced by functions which will be called to with the corresponding value in the input.
For validating dictionaries that represent a mapping from one set of values to another, use
validate_mapping()
.A simple example:
validator = validate_structure(schema={ 'id': validate_key(kind='Model'), 'count': validate_int(min=0), }) validator({'id': self.key, 'count': self.count})
Parameters: - value (dict) – The value to be validated.
- schema (dict) – The schema against which the value should be checked.
- allow_extra (bool) – Set to True to ignore extra keys.
- required (bool) – Whether the value can’t be None. Defaults to True.