Reference

Abstract

class validx.py.Validator(alias=None, replace=False)[source]

Abstract Base Validator

Parameters:
  • alias (str) – if it specified, the instance will be added into registry, see validx.py.instances.add().
  • replace (bool) – if it is True and alias specified, the instance will be added into registry, replacing any existent validator with the same alias, see validx.py.instances.put().
  • **kw – concrete validator attributes.
__call__(value, _Validator__context=None)[source]

Validate value.

This is an abstract method, and it should be implemented by descendant class.

static load(params, update=None, unset=None, **kw)[source]

Load validator.

>>> Validator.load({
...     "__class__": "Int",
...     "min": 0,
...     "max": 100,
... })
<Int(min=0, max=100)>

>>> # Add into registry
>>> some_int = Validator.load({
...     "__class__": "Int",
...     "min": 0,
...     "max": 100,
...     "alias": "some_int",
... })
>>> some_int
<Int(min=0, max=100)>

>>> # Load from registry by alias
>>> Validator.load({"__use__": "some_int"}) is some_int
True

>>> # Clone from registry by alias
>>> Validator.load({
...     "__clone__": "some_int",
...     "update": {
...         "min": -100,
...     },
... })
<Int(min=-100, max=100)>
dump()[source]

Dump validator.

>>> Int(min=0, max=100).dump() == {
...     "__class__": "Int",
...     "min": 0,
...     "max": 100,
... }
True
clone(update=None, unset=None, **kw)[source]

Clone validator.

>>> some_enum = Int(options=[1, 2, 3])
>>> some_enum.clone(
...     {
...         "nullable": True,
...         "options+": [4, 5],
...         "options-": [1, 2],
...     }
... ) == Int(nullable=True, options=[3, 4, 5])
True

In fact, the method is a shortcut for:

self.load(self.dump(), update, **kw)

Numbers

class validx.py.Int(nullable=False, coerce=False, min=None, max=None, options=None, alias=None, replace=False)[source]

Integer Number Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • coerce (bool) – try to convert non-integer value to int.
  • min (int) – lower limit.
  • max (int) – upper limit.
  • options (iterable) – explicit enumeration of valid values.
Raises:
Note:

It implicitly converts float to int, if value.is_integer() is True.

class validx.py.Float(nullable=False, coerce=False, nan=False, inf=False, min=None, max=None, alias=None, replace=False)[source]

Floating Point Number Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • coerce (bool) – try to convert non-float value to float.
  • nan (bool) – accept Not-a-Number as a valid value.
  • inf (bool) – accept Infinity as a valid value.
  • min (float) – lower limit.
  • max (float) – upper limit.
Raises:
  • InvalidTypeError
    • if value is None and not self.nullable;
    • if not isinstance(value, float) and not self.coerce.
  • CoerceError – if self.coerce and float(value) raises an exception.
  • NumberError
    • if math.isnan(value) and not self.nan;
    • if math.isinf(value) and not self.inf.
  • MinValueError – if value < self.min.
  • MaxValueError – if value > self.max.
Note:

It always converts int to float.

class validx.py.Decimal(nullable=False, coerce=False, precision=None, nan=False, inf=False, min=None, max=None, alias=None, replace=False)[source]

Fixed Point Number Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • coerce (bool) – try to convert non-decimal value to decimal.Decimal.
  • precision (int) – number of decimal places after point.
  • nan (bool) – accept Not-a-Number as a valid value.
  • inf (bool) – accept Infinity as a valid value.
  • min (decimal.Decimal) – lower limit.
  • max (decimal.Decimal) – upper limit.
Raises:
  • InvalidTypeError
    • if value is None and not self.nullable;
    • if not isinstance(value, decimal.Decimal) and not self.coerce.
  • CoerceError – if self.coerce and decimal.Decimal(value) raises an exception.
  • NumberError
    • if value.is_nan() and not self.nan;
    • if value.is_infinite() and not self.inf.
  • MinValueError – if value < self.min.
  • MaxValueError – if value > self.max.
Note:

It always converts int and float to decimal.Decimal.

Chars

class validx.py.Str(nullable=False, coerce=False, dontstrip=False, normspace=False, encoding=None, minlen=None, maxlen=None, pattern=None, options=None, alias=None, replace=False)[source]

Unicode String Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • coerce (bool) – convert non-string value to str, use with caution (see notes below).
  • dontstrip (bool) – do not strip leading & trailing whitespace.
  • normspace (bool) – normalize spaces, i.e. replace any space sequence by single space char.
  • encoding (str) – try to decode bytes to str using specified encoding.
  • minlen (int) – lower length limit.
  • maxlen (int) – upper length limit.
  • pattern (str) – validate string using regular expression.
  • options (iterable) – explicit enumeration of valid values.
Raises:
Note:

Since any Python object can be converted to a string, using coerce without other checks in fact validates nothing. It can be useful though to sanitize data from sources with automatic type inferring, where string data might be incorrectly interpreted as another type. For example, phone number as int, version number as float, etc.

class validx.py.Bytes(nullable=False, minlen=None, maxlen=None, alias=None, replace=False)[source]

Byte String Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • minlen (int) – lower length limit.
  • maxlen (int) – upper length limit.
Raises:

Date and Time

class validx.py.Date(nullable=False, unixts=False, format=None, parser=None, min=None, max=None, relmin=None, relmax=None, tz=None, alias=None, replace=False)[source]

Date Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • unixts (bool) – convert Unix timestamp (int or float) to date.
  • format (str) – try to parse date from str using datetime.strptime(value, self.format).date().
  • parser (callable) – try to parse date from str using self.parser(value).date().
  • min (date) – absolute lower limit.
  • max (date) – absolute upper limit.
  • relmin (timedelta) – relative lower limit.
  • relmax (timedelta) – relative upper limit.
  • tz (tzinfo) – timezone, see notes below.
Raises:
  • InvalidTypeError
    • if value is None and not self.nullable;
    • if isinstance(value, (int, float)) and not self.unixts;
    • if isinstance(value, bool) and self.unixts, because issubclass(bool, int) is True, but it is very unlikely bool could represent a valid timestamp;
    • if not isinstance(value, date).
  • DatetimeParseError
    • if datetime.strptime(value, self.format) raises ValueError;
    • if self.parser(value) raises ValueError.
  • MinValueError
    • if value < self.min;
    • if value < date.today() + self.relmin;
    • if self.unixts and value lesser than the minimal supported timestamp.
  • MaxValueError
    • if value > self.max;
    • if value > date.today() + self.relmax;
    • if self.unixts and value greater than the maximal supported timestamp.
Note:

Relative limits are calculated adding deltas to current date, use negative relmin/relmax to specify date in the past.

Note:

It implicitly converts datetime to date. If timezone is specified and datetime object is timezone-aware, it will be arranged to specified timezone first.

Note:

If timezone is specified, it will be used in conversion from Unix timestamp. In fact, it will create datetime object in UTC, using datetime.fromtimestamp(value, UTC). And then arrange it to specified timezone, and extract date part. It also will be used in the same way to get today value for relmin/relmax checks, i.e. datetime.now(UTC).astimezone(self.tz).date().

class validx.py.Time(nullable=False, format=None, parser=None, min=None, max=None, alias=None, replace=False)[source]

Time Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • format (str) – try to parse time from str using datetime.strptime(value, self.format).time().
  • parser (callable) – try to parse time from str using self.parser(value).time().
  • min (time) – lower limit.
  • max (time) – upper limit.
Raises:
class validx.py.Datetime(nullable=False, unixts=False, format=None, parser=None, min=None, max=None, relmin=None, relmax=None, default_time=None, tz=None, alias=None, replace=False)[source]

Date & Time Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • unixts (bool) – convert Unix timestamp (int or float) to datetime.
  • format (str) – try to parse datetime from str using datetime.strptime(value, self.format).
  • parser (callable) – try to parse datetime from str using self.parser(value).
  • min (datetime) – absolute lower limit.
  • max (datetime) – absolute upper limit.
  • relmin (timedelta) – relative lower limit.
  • relmax (timedelta) – relative upper limit.
  • default_time (time) – is used to implicitly convert date to datetime using datetime.combine(value, self.default_time or time(tzinfo=self.tz)).
  • tz (tzinfo) – timezone.
Raises:
  • InvalidTypeError
    • if value is None and not self.nullable;
    • if isinstance(value, (int, float)) and not self.unixts;
    • if isinstance(value, bool) and self.unixts, because issubclass(bool, int) is True, but it is very unlikely bool could represent a valid timestamp;
    • if not isinstance(value, datetime).
  • DatetimeParseError
    • if datetime.strptime(value, self.format) raises ValueError;
    • if self.parser(value) raises ValueError.
  • DatetimeTypeError
    • if self.tz is None and value.tzinfo is not None;
    • if self.tz is not None and value.tzinfo is None;
  • MinValueError
    • if value < self.min;
    • if self.tz is None and value < datetime.now() + self.relmin.
    • if self.tz is not None and value < datetime.now(UTC).astimezone(self.tz) + self.relmin;
    • if self.unixts and value lesser than the minimal supported timestamp.
  • MaxValueError
    • if value > self.max;
    • if self.tz is None and value > datetime.now() + self.relmax.
    • if self.tz is not None and value > datetime.now(UTC).astimezone(self.tz) + self.relmax;
    • if self.unixts and value greater than the maximal supported timestamp.

Boolean

class validx.py.Bool(nullable=False, coerce_str=False, coerce_int=False, alias=None, replace=False)[source]

Boolean Validator

Parameters:
  • nullable (bool) – accept None as a valid value.
  • coerce_str (bool) –
    • accept values ["1", "true", "yes", "y", "on"] as True;
    • accept values ["0", "false", "no", "n", "off"] as False.
  • coerce_int (bool) – accept int as valid value.
Raises:
  • InvalidTypeError
    • if value is None and not self.nullable;
    • if isinstance(value, str) and not self.coerce_str;
    • if isinstance(value, int) and not self.coerce_int;
    • if not isinstance(value, bool).
  • OptionsError – when string value is not valid name, see coerce_str.

Containers

class validx.py.List(item, nullable=False, sort=None, sort_key=None, minlen=None, maxlen=None, unique=False, alias=None, replace=False)[source]

List Validator

Parameters:
  • item (Validator) – validator for list items.
  • nullable (bool) – accept None as a valid value.
  • sort (int) – 1 for ascending, -1 for descending.
  • sort_key (callable) – function to extract a comparison key.
  • minlen (int) – lower length limit.
  • maxlen (int) – upper length limit.
  • unique (bool) – drop duplicate items.
Raises:
class validx.py.Set(item, nullable=False, minlen=None, maxlen=None, alias=None, replace=False)[source]

Set Validator

Parameters:
  • item (Validator) – validator for set items.
  • nullable (bool) – accept None as a valid value.
  • minlen (int) – lower length limit.
  • maxlen (int) – upper length limit.
Raises:
class validx.py.Tuple(*items_, items=None, nullable=False, alias=None, replace=False)[source]

Tuple Validator

Parameters:
  • *items (Validator) – validators for tuple members.
  • nullable (bool) – accept None as a valid value.
Raises:
class validx.py.Dict(schema=None, nullable=False, minlen=None, maxlen=None, extra=None, defaults=None, optional=None, dispose=None, multikeys=None, alias=None, replace=False)[source]

Dictionary Validator

Parameters:
  • schema (dict) – schema validator in format {<key>: <validator>}.
  • nullable (bool) – accept None as a valid value.
  • minlen (int) – lower length limit.
  • maxlen (int) – upper length limit.
  • extra (tuple) – validators for extra keys and values in format (<key_validator>, <value_validator>), it is used for keys are not presented in schema.
  • defaults (dict) – default values for missing keys.
  • optional (list or tuple) – list of optional keys.
  • dispose (list or tuple) – list of keys that have to be silently removed.
  • multikeys (list or tuple) – list of keys that have to be treated as lists of values, if input value is a MultiDict (see notes below), i.e. value of these keys will be extracted using val = value.getall(key) or val = value.getlist(key).
Raises:
  • InvalidTypeError – if not isinstance(value, collections.abc.Mapping).
  • MinLengthError – if len(value) < self.minlen.
  • MaxLengthError – if len(value) > self.maxlen.
  • SchemaError – with all errors, raised by schema validators, extra validators, and missing required and forbidden extra keys.
Note:

on error raised by extra validators, context marker validx.exc.Extra will be used to indicate, which part of key/value pair is failed.

It has been tested against the following implementations of MultiDict:

However, it should work fine for other implementations, if the implementation is subclass of collections.abc.Mapping, and provides getall() or getlist() methods.

Pipelines

class validx.py.AllOf(*steps_, steps=None, alias=None, replace=False)[source]

AND-style Pipeline Validator

All steps must be succeeded. The last step returns result.

Parameters:*steps (Validator) – nested validators.
Raises:ValidationError – raised by the first failed step.
Note:it uses validx.exc.Step marker to indicate, which step is failed.
class validx.py.OneOf(*steps_, steps=None, alias=None, replace=False)[source]

OR-style Pipeline Validator

The first succeeded step returns result.

Parameters:*steps (Validator) – nested validators.
Raises:SchemaError – if all steps are failed, so it contains all errors, raised by each step.
Note:it uses validx.exc.Step marker to indicate, which step is failed.

Special

class validx.py.LazyRef(use, maxdepth=None, alias=None, replace=False)[source]

Lazy Referenced Validator

It is useful to build validators for recursive structures.

>>> schema = Dict(
...     {
...         "foo": Int(),
...         "bar": LazyRef("schema", maxdepth=1),
...     },
...     optional=("foo", "bar"),
...     minlen=1,
...     alias="schema",
... )

>>> schema({"foo": 1})
{'foo': 1}

>>> schema({"bar": {"foo": 1}})
{'bar': {'foo': 1}}

>>> schema({"bar": {"bar": {"foo": 1}}})
Traceback (most recent call last):
    ...
validx.exc.errors.SchemaError: <SchemaError(errors=[
    <bar.bar: RecursionMaxDepthError(expected=1, actual=2)>
])>
Parameters:
  • use (str) – alias of referenced validator.
  • maxdepth (int) – maximum recursion depth.
Raises:

RecursionMaxDepthError – if self.maxdepth is not None and current recursion depth exceeds the limit.

class validx.py.Type(tp, nullable=False, coerce=False, min=None, max=None, minlen=None, maxlen=None, options=None, alias=None, replace=False)[source]

Custom Type Validator

Parameters:
  • tp (type) – valid value type.
  • nullable (bool) – accept None as a valid value.
  • coerce (bool) – try to convert value to tp.
  • min (tp) – lower limit, makes sense only if tp provides comparison methods.
  • max (tp) – upper limit, makes sense only if tp provides comparison methods.
  • minlen (int) – lower length limit, makes sense only if tp provides __len__() method.
  • maxlen (int) – upper length limit, makes sense only if tp provides __len__() method.
  • options (iterable) – explicit enumeration of valid values.
Raises:
class validx.py.Const(value, alias=None, replace=False)[source]

Constant Validator

It only accepts single predefined value.

Parameters:value – expected valid value.
Raises:OptionsError – if value != self.value.
class validx.py.Any(alias=None, replace=False)[source]

Pass-Any Validator

It literally accepts any value.

Class Registry

validx.py.classes.add(class_)[source]

Add validator class into the registry

Parameters:class (Validator) – class to register.
Raises:AssertionError – if there is a class in the registry with the same name, i.e. class_.__name__.
Returns:unmodified passed class, so the function can be used as a decorator.
validx.py.classes.get(classname)[source]

Get validator class from the registry

Parameters:classname (str) – name of class to get.
Raises:KeyError – if there is no class in the registry with the specified name.
Returns:previously registered class.

Instance Registry

validx.py.instances.add(alias, instance)[source]

Add validator into the registry

Parameters:
  • alias (str) – alias of the validator.
  • instance (Validator) – instance of the validator.
Raises:

AssertionError – if there is an instance in the registry with the same alias.

Returns:

unmodified instance of passed validator.

validx.py.instances.put(alias, instance)[source]

Put validator into the registry

The function silently replaces any instance with the same alias.

Parameters:
  • alias (str) – alias of the validator.
  • instance (Validator) – instance of the validator.
Returns:

unmodified instance of passed validator.

validx.py.instances.get(alias)[source]

Get validator from the registry

Parameters:alias (str) – alias of the validator.
Raises:KeyError – if there is no registered validator under the specified alias.
Returns:previously registered validator.
validx.py.instances.clear()[source]

Clear the registry

Errors

The class hierarchy for exceptions is:

class validx.exc.ValidationError(context=None, *args, **kw)[source]

Validation Error Base Class

Parameters:
  • context (deque) – error context, empty deque by default.
  • **kw – concrete error attributes.

Since validators try to process as much as possible, they can raise multiple errors (wrapped by validx.exc.SchemaError). To unify handling of such errors, each validation error provides Sequence interface. It means, you can iterate them, get their length, get nested errors by index, and sort nested errors by context.

Error context is a full path, that indicates where the error occurred. It contains mapping keys, sequence indexes, and special markers (see validx.exc.Extra and validx.exc.Step).

>>> from validx import exc, Dict, List, Int

>>> schema = Dict({"foo": List(Int(max=100))})
>>> try:
...     schema({"foo": [1, 2, 200, 250], "bar": None})
... except exc.ValidationError as e:
...     error = e

>>> error.sort()
>>> error
<SchemaError(errors=[
    <bar: ForbiddenKeyError()>,
    <foo.2: MaxValueError(expected=100, actual=200)>,
    <foo.3: MaxValueError(expected=100, actual=250)>
])>

>>> len(error)
3

>>> error[1]
<foo.2: MaxValueError(expected=100, actual=200)>
>>> error[1].context
deque(['foo', 2])
>>> error[1].format_context()
'foo.2'
>>> error[1].format_error()
'MaxValueError(expected=100, actual=200)'

>>> error.sort(reverse=True)
>>> error
<SchemaError(errors=[
    <foo.3: MaxValueError(expected=100, actual=250)>,
    <foo.2: MaxValueError(expected=100, actual=200)>,
    <bar: ForbiddenKeyError()>
])>
add_context(node)[source]

Add error context

Parameters:node – key or index of member, where error is raised.
Returns:the error itself, so that the method is suitable for chaining.

Example:

>>> from validx.exc import ValidationError

>>> e = ValidationError()
>>> e
<ValidationError()>
>>> e.context
deque([])

>>> e.add_context("foo")
<foo: ValidationError()>
>>> e.context
deque(['foo'])
class validx.exc.ConditionError(context=None, *args, **kw)[source]

Base Class for Condition Errors

It has a couple of attributes expected and actual, that gives info of what happens and why the error is raised.

See derived classes for details.

class validx.exc.InvalidTypeError(context=None, *args, **kw)[source]

Invalid Type Error

Parameters:
  • expected (type or tuple) – expected type (types).
  • actual (type) – actual type of value.
class validx.exc.CoerceError(context=None, *args, **kw)[source]

Coerce Error

Parameters:
  • expected (type) – expected type.
  • actual – actual value.
class validx.exc.OptionsError(context=None, *args, **kw)[source]

Options Error

Parameters:
  • expected (list or tuple) – list of valid values.
  • actual – actual value.
class validx.exc.MinValueError(context=None, *args, **kw)[source]

Minimum Value Error

Parameters:
  • expected – minimal allowed value.
  • actual – actual value.
class validx.exc.MaxValueError(context=None, *args, **kw)[source]

Maximum Value Error

Parameters:
  • expected – maximal allowed value.
  • actual – actual value.
class validx.exc.NumberError(context=None, *args, **kw)[source]

Number Error

Parameters:
  • expected (str) –
    • "number" on test for Not-a-Number;
    • "finite" on test for Infinity.
  • actual (float or decimal.Decimal) – actual value.
class validx.exc.StrDecodeError(context=None, *args, **kw)[source]

String Decode Error

Parameters:
  • expected (str) – encoding name.
  • actual (bytes) – actual byte-string value.
class validx.exc.MinLengthError(context=None, *args, **kw)[source]

Minimum Length Error

Parameters:
  • expected (int) – minimal allowed length.
  • actual (int) – actual value length.
class validx.exc.MaxLengthError(context=None, *args, **kw)[source]

Maximum Length Error

Parameters:
  • expected (int) – maximal allowed length.
  • actual (int) – actual value length.
class validx.exc.TupleLengthError(context=None, *args, **kw)[source]

Tuple Length Error

Parameters:
  • expected (int) – tuple length.
  • actual (int) – actual value length.
class validx.exc.PatternMatchError(context=None, *args, **kw)[source]

Pattern Match Error

Parameters:
  • expected (str) – pattern, i.e. regular expression.
  • actual (str) – actual value.
class validx.exc.DatetimeParseError(context=None, *args, **kw)[source]

Date & Time Parse Error

Parameters:
  • expected (str) – format.
  • actual (str) – actual value.
class validx.exc.DatetimeTypeError(context=None, *args, **kw)[source]

Date & Time Type Error

Parameters:
  • expected (str) – expected type of datetime: “naive” or “tzaware”.
  • actual (datetime) – actual value.
class validx.exc.RecursionMaxDepthError(context=None, *args, **kw)[source]

Recursion Maximum Depth Error

Parameters:
  • expected (int) – maximal allowed depth.
  • actual (int) – actual recursion depth.
class validx.exc.MappingKeyError(context=None, key=None)[source]

Base Class for Mapping Key Errors

Parameters:key – failed key, that goes into error context.
>>> e = MappingKeyError("foo")
>>> e
<foo: MappingKeyError()>
class validx.exc.ForbiddenKeyError(context=None, key=None)[source]

Forbidden Mapping Key Error

class validx.exc.MissingKeyError(context=None, key=None)[source]

Missing Mapping Key Error

class validx.exc.SchemaError(context=None, errors=None)[source]

Schema Error

It is an error class, that wraps multiple errors occurred during complex structure validation.

Parameters:errors (list) – list of all errors occurred during complex structure validation.

Context Markers

class validx.exc.Extra(name)[source]

Extra Key Context Marker

It is a special context marker, that is used by mapping validators to indicate, which part of extra key/value pair is failed.

There are two constants in the module:

  • EXTRA_KEY indicates that key validation is failed;
  • EXTRA_VALUE indicates that value validation is failed.

It has special representation, to be easily distinguished from other string keys.

Parameters:name (str) – name of pair part, i.e. KEY or VALUE.
>>> from validx import exc, Dict, Str

>>> schema = Dict(extra=(Str(maxlen=2), Str(maxlen=4)))
>>> try:
...     schema({"xy": "abc", "xyz": "abcde"})
... except exc.ValidationError as e:
...     error = e

>>> error
<SchemaError(errors=[
    <xyz.@KEY: MaxLengthError(expected=2, actual=3)>,
    <xyz.@VALUE: MaxLengthError(expected=4, actual=5)>
])>

>>> repr(error[0].context[1])
'@KEY'
>>> error[0].context[1].name
'KEY'

>>> error[0].context[1] is exc.EXTRA_KEY
True
>>> error[1].context[1] is exc.EXTRA_VALUE
True
class validx.exc.Step(num)[source]

Step Number Context Marker

It is a special context marker, that is used by pipeline validators to indicate, which validation step is failed. It has special representation, to be easily distinguished from sequence indexes.

Parameters:num (int) – number of failed step.
>>> from validx import exc, OneOf, Int

>>> schema = OneOf(Int(min=0, max=10), Int(min=90, max=100))
>>> try:
...     schema(50)
... except exc.ValidationError as e:
...     error = e

>>> error
<SchemaError(errors=[
    <#0: MaxValueError(expected=10, actual=50)>,
    <#1: MinValueError(expected=90, actual=50)>
])>

>>> repr(error[0].context[0])
'#0'
>>> error[0].context[0].num
0
>>> isinstance(error[0].context[0], exc.Step)
True

Error Formatter

class validx.exc.Formatter(templates)[source]

Error Formatter

Parameters:templates (dict) – templates that will be used to format errors.

Each key of templates should be a subclass of validx.exc.ValidationError.

Each value of templates should be a string, i.e. simple template, or list of conditional templates.

Conditional template is a tuple (predicate, string). Where predicate is a callable, that accepts validx.exc.ValidationError and returns boolean value. When the predicate evaluates to True, its corresponding string will be used as a template.

Last value of list of conditional templates can be a string, i.e. default simple template.

See format_error object, defined within the module, as an example.

__call__(error)[source]

Format Error

Parameters:error (ValidationError) – error to format.
Returns:list of context/message pairs: [(str, str), ...].