Included Validators¶
Scalars¶
-
class
Present(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates that a value is present.
Messages
-
missing¶ Emitted if the
ustring value of the element is empty, as in the case for an HTML form submitted with an input box left blank.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
IsTrue(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates that a value evaluates to true.
Messages
-
false¶ Emitted if
bool(element.value)is not True.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
IsFalse(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates that a value evaluates to false.
Messages
-
true¶ Emitted if
bool(element.value)is not False.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueIn(valid_options=Unspecified, **kw)¶ Bases:
flatland.validation.base.ValidatorValidates that the value is within a set of possible values.
Example:
import flatland from flatland.validation import ValueIn is_yesno = ValueIn(valid_options=['yes', 'no']) schema = flatland.String('yn', validators=[is_yesno])
Attributes
-
valid_options¶ A list, set, or other container of valid element values.
Messages
-
fail¶ Emitted if the element’s value is not within the valid_options.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
Converted(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates that an element was converted to a Python value.
Example:
import flatland from flatland.validation import Converted not_bogus = Converted(incorrect='Please enter a valid date.') schema = flatland.DateTime('when', validators=[not_bogus])
Messages
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ShorterThan(maxlength=Unspecified, **kw)¶ Bases:
flatland.validation.base.ValidatorValidates the length of an element’s string value is less than a bound.
Example:
import flatland from flatland.validation import ShorterThan valid_length = ShorterThan(8) schema = flatland.String('password', validators=[valid_length])
Attributes
-
maxlength¶ A maximum character length for the
u.This attribute may be supplied as the first positional argument to the constructor.
Messages
-
exceeded¶ Emitted if the length of the element’s string value exceeds maxlength.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
NoLongerThan¶
-
class
LongerThan(minlength=Unspecified, **kw)¶ Bases:
flatland.validation.base.ValidatorValidates the length of an element’s string value is more than a bound.
Example:
import flatland from flatland.validation import LongerThan valid_length = LongerThan(4) schema = flatland.String('password', validators=[valid_length])
Attributes
-
minlength¶ A minimum character length for the
u.This attribute may be supplied as the first positional argument to the constructor.
Messages
-
short¶ Emitted if the length of the element’s string value falls short of minlength.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
LengthBetween(minlength=Unspecified, maxlength=Unspecified, **kw)¶ Bases:
flatland.validation.base.ValidatorValidates the length of an element’s string value is within bounds.
Example:
import flatland from flatland.validation import LengthBetween valid_length = LengthBetween(4, 8) schema = flatland.String('password', validators=[valid_length])
Attributes
-
minlength¶ A minimum character length for the
u.This attribute may be supplied as the first positional argument to the constructor.
-
maxlength¶ A maximum character length for the
u.This attribute may be supplied as the second positional argument to the constructor.
Messages
-
breached¶ Emitted if the length of the element’s string value is less than minlength or greater than maxlength.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueLessThan(boundary, **kw)¶ Bases:
flatland.validation.base.ValidatorA validator that ensures that the value is less than a limit.
Example:
import flatland from flatland.validation import ValueLessThan schema = flatland.Integer('wishes', validators=[ValueLessThan(boundary=4)])
Attributes
-
boundary¶ Any comparable object.
Messages
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueAtMost(maximum, **kw)¶ Bases:
flatland.validation.base.ValidatorA validator that enforces a maximum value.
Example:
import flatland from flatland.validation import ValueAtMost schema = flatland.Integer('wishes', validators=[ValueAtMost(maximum=3)])
Attributes
-
maximum¶ Any comparable object.
Messages
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueGreaterThan(boundary, **kw)¶ Bases:
flatland.validation.base.ValidatorA validator that ensures that a value is greater than a limit.
Example:
import flatland from flatland.validation import ValueGreaterThan schema = flatland.Integer('wishes', validators=[ValueGreaterThan(boundary=4)])
Attributes
-
boundary¶ Any comparable object.
Messages
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueAtLeast(minimum, **kw)¶ Bases:
flatland.validation.base.ValidatorA validator that enforces a minimum value.
Example:
import flatland from flatland.validation import ValueAtLeast schema = flatland.Integer('wishes', validators=[ValueAtLeast(minimum=3)])
Attributes
-
minimum¶ Any comparable object.
Messages
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValueBetween(minimum, maximum, **kw)¶ Bases:
flatland.validation.base.ValidatorA validator that enforces minimum and maximum values.
Example:
import flatland from flatland.validation import ValueBetween schema = flatland.Integer('wishes', validators=[ValueBetween(minimum=1, maximum=3)])
Attributes
-
minimum¶ Any comparable object.
-
maximum¶ Any comparable object.
-
inclusive¶ Boolean value indicating that
minimumandmaximumare included in the range. Defaults to True.
Messages
-
failure_inclusive¶ Emitted when
inclusiveis True if the expressionminimum<= value <=maximumevaluates to False.
-
failure_exclusive¶ Emitted when
inclusiveis False if the expressionminimum< value <maximumevaluates to False.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
MapEqual(*field_paths, **kw)¶ Bases:
flatland.validation.base.ValidatorA general field equality validator.
Validates that two or more fields are equal.
Attributes
-
field_paths¶ A sequence of field names or field paths. Path names will be evaluated at validation time and relative path names are resolved relative to the element holding this validator. See
ValuesEqualfor an example.
Messages
-
unequal¶ Emitted if the
transform(element)of all elements are not equal.labelswill substitute to a comma-separated list of thelabelof all but the last element;last_labelis the label of the last.
Construct a MapEqual.
Parameters: - *field_paths – a sequence of 2 or more elements names or paths.
- **kw – passed to
Validator.__init__().
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
ValuesEqual(*field_paths, **kw)¶ Bases:
flatland.validation.scalars.MapEqualValidates that the values of multiple elements are equal.
A
MapEqualthat compares thevalueof each element.Example:
from flatland import Schema, String from flatland.validation import ValuesEqual class MyForm(Schema): password = String password_again = String validators = [ValuesEqual('password', 'password_again')]
-
transform¶ attrgetter(‘value’)
Construct a MapEqual.
Parameters: - *field_paths – a sequence of 2 or more elements names or paths.
- **kw – passed to
Validator.__init__().
-
-
class
UnisEqual(*field_paths, **kw)¶ Bases:
flatland.validation.scalars.MapEqualValidates that the Unicode values of multiple elements are equal.
A
MapEqualthat compares theuof each element.-
transform¶ attrgetter(‘u’)
Construct a MapEqual.
Parameters: - *field_paths – a sequence of 2 or more elements names or paths.
- **kw – passed to
Validator.__init__().
-
Containers¶
-
class
NotDuplicated(**kw)¶ Bases:
flatland.validation.base.ValidatorA sequence member validator that ensures all sibling values are unique.
Marks the second and any subsequent occurrences of a value as invalid. Only useful on immediate children of sequence fields such as
flatland.List.Example:
import flatland from flatland.schema.containers import List from flatland.validation import NotDuplicated validator = NotDuplicated(failure="Please enter each color only once.") schema = List.of(String.named('favorite_color')).\ using(validators=[validator])
Attributes
-
comparator¶ A callable boolean predicate, by default
operator.eq. Called positionally with two arguments, element and sibling.Can be used as a filter, for example ignoring any siblings that have been marked as “deleted” by a checkbox in a web form:
from flatland import Schema, List, String, Integer, Boolean from flatland.validation import NotDuplicated def live_addrs(element, sibling): thisval, thatval = element.value, sibling.value # data marked as deleted is never considered a dupe if thisval['deleted'] or thatval['deleted']: return False # compare elements on 'street' & 'city', ignoring 'id' return (thisval['street'] == thatval['street'] and thisval['city'] == thatval['city']) class Address(Schema): validators = [NotDuplicated(comparator=live_addrs)] id = Integer.using(optional=True) deleted = Boolean street = String city = String schema = List.of(Address)
Messages
-
failure¶ Emitted on an element that has already appeared in a parent sequence.
container_labelwill substitute the label of the container.positionis the position of the element in the parent sequence, counting up from 1.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
comparator() eq(a, b) – Same as a==b.
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
HasAtLeast(**kw)¶ Bases:
flatland.validation.base.ValidatorA sequence validator that ensures a minimum number of members.
May be applied to a sequence type such as a
List.Example:
from flatland import List, String from flatland.validation import HasAtLeast schema = List.of(String.named('wish')).\ using(validators=[HasAtLeast(minimum=3)])
Attributes
-
minimum¶ Any positive integer.
Messages
-
failure¶ Emitted if the sequence contains less than
minimummembers.child_labelwill substitute the label of the child schema.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
HasAtMost(**kw)¶ Bases:
flatland.validation.base.ValidatorA sequence validator that ensures a maximum number of members.
May be applied to a sequence type such as a
List.Example:
from flatland import List, String from flatland.validation import HasAtMost schema = List.of(String.named('wish')).\ using(validators=[HasAtMost(maximum=3)])
Attributes
-
maximum¶ Any positive integer.
Messages
-
failure¶ Emitted if the sequence contains more than
maximummembers.child_labelwill substitute the label of the child schema.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
HasBetween(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates that the number of members of a sequence lies within a range.
May be applied to a sequence type such as a
List.Example:
from flatland import List, String from flatland.validation import HasBetween schema = List.of(String.named('wish')).\ using(validators=[HasBetween(minimum=1, maximum=3)])
Attributes
-
minimum¶ Any positive integer.
-
maximum¶ Any positive integer.
Messages
-
range¶ Emitted if the sequence contains fewer than
minimummembers or more thanmaximummembers.child_labelwill substitute the label of the child schema.
-
exact¶ Like
range, however this message is emitted ifminimumandmaximumare the same.schema = List.of(String.named('wish')).\ using(validators=[HasBetween(minimum=3, maximum=3)])
-
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
SetWithKnownFields(**kw)¶ Bases:
flatland.validation.base.ValidatorA mapping validator that ensures no unexpected fields were set().
May be applied to a mapping type such as a
Dict.Example:
from flatland import Dict, Integer from flatland.validation import SetWithKnownFields schema = Dict.of(Integer.named('x'), Integer.named('y')).\ validated_by(SetWithKnownFields()) schema.policy = None element = schema() element.set({'x': 123, 'y': 456}) assert element.validate() element.set({'x': 123, 'y': 456, 'z': 789}) assert not element.validate()
#from flatland import Dict, Integer #from flatland.validation import SetWithKnownFields # #schema = Dict.of(Integer.named('x'), Integer.named('y')).\ # validated_by(SetWithKnownFields()) #schema.policy = None #element = schema() # #element.set({'x': 123}) #assert element.validate() # assertion error, issue #25, FIXME! # #element.set({'x': 123, 'z': 789}) #assert not element.validate() # no assertion error, but maybe due to #25 also.
This validator collects the keys from
rawand compares them to the allowed keys for the element. Only elements in whichrawis available and iterable will be considered for validation; all others are deemed valid.Warning
This validator will not enforce policy on mappings initialized with
set_flat()because raw is unset.Note
This validator obsoletes and deprecates the
Dict.policy = 'subset'feature. During the deprecation period, policy is still enforced byset()by default. To allow this validator to run, disable the default by settingpolicy = Noneon the element or its schema.Messages
-
unexpected¶ Emitted if the initializing value contains unexpected keys.
unexpectedwill substitute a comma-separated list of unexpected keys, andn_unexpecteda count of those keys.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
class
SetWithAllFields(**kw)¶ Bases:
flatland.validation.base.ValidatorA mapping validator that ensures all fields were set().
May be applied to a mapping type such as a
Dict.Example:
from flatland import Dict, Integer from flatland.validation import SetWithAllFields schema = Dict.of(Integer.named('x'), Integer.named('y')).\ validated_by(SetWithAllFields()) schema.policy = None element = schema() element.set({'x': 123, 'y': 456}) assert element.validate() element.set({'x': 123}) assert not element.validate() element.set({'x': 123, 'y': 456, 'z': 789}) assert not element.validate()
This validator collects the keys from
rawand compares them to the allowed keys for the element. Only elements in whichrawis available and iterable will be considered for validation; all others are deemed valid.Warning
This validator will not enforce policy on mappings initialized with
set_flat()because raw is unset.Note
This validator obsoletes and deprecates the
Dict.policy = 'strict'feature. During the deprecation period, policy is still enforced byset()by default. To allow this validator to run, disable the default by settingpolicy = Noneon the element or its schema.Messages
-
unexpected¶ Emitted if the initializing value contains unexpected keys.
unexpectedwill substitute a comma-separated list of unexpected keys, andn_unexpecteda count of those keys.
-
missing¶ Emitted if the initializing value did not contain all expected keys.
missingwill substitute a comma-separated list of missing keys, andn_missinga count of those keys.
-
both¶ Emitted if both of the previous conditions hold, and both sets of substitution keys are available.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
Numbers¶
-
class
Luhn10(**kw)¶ Bases:
flatland.validation.base.ValidatorTrue if a numeric value passes luhn10 checksum validation.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
validate(element, state)¶ Validate an element returning True if valid.
Abstract.
Parameters: - element – an
Elementinstance. - state – an arbitrary object. Supplied by
Element.validate.
Returns: True if valid
- element – an
-
-
luhn10_check(number)¶ Return True if the number passes the Luhn checksum algorithm.
Email Addresses¶
-
class
IsEmail(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates email addresses.
The default behavior takes a very permissive stance on allowed characters in the local-part and a relatively strict stance on the domain. Given local-part@domain:
- local-part must be present and contain at least one non-whitespace character. Any character is permitted, including international characters.
- domain must be preset, less than 253 characters and each dot-separated component must be 63 characters or less. domain may contain non-ASCII international characters, and will be converted to IDN representation before length assertions are applied. No top level domain validations are applied.
Attributes
-
non_local¶ Default
True. When true, require at minimum two domain name components and reject local email addresses such aspostmaster@localhostoruser@workstation.
-
local_part_pattern¶ No default. If present, a compiled regular expression that will be matched to the local-part. Override this to implement more stringent checking such as RFC-compliant addresses.
-
domain_pattern¶ Defaults to a basic domain-validating regular expression with no notion of valid top level domains. Override this to require certain TLDs (or alternately and more simply, add another validator to your chain that checks the endings of the string against your list of TLDs.)
The default pattern rejects the valid but obscure quoted IP-address form (
[1.2.3.4]).
Messages
-
invalid¶ Emitted if the email address is not valid.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance.
URLs¶
-
class
URLValidator(**kw)¶ Bases:
flatland.validation.base.ValidatorA general URL validator.
Validates that a URL is well-formed and may optionally restrict the set of valid schemes and other URL components.
Attributes
-
allowed_schemes¶ Restrict URLs to just this sequence of named schemes, or allow all schemes with (‘*’,). Defaults to all schemes. Example:
allowed_schemes = ('http', 'https', 'ssh')
-
allowed_parts¶ A sequence of 0 or more part names in
urlparse’s vocabulary:'scheme', 'netloc', 'path', 'params', 'query', 'fragment'
Defaults to all parts allowed.
-
urlparse¶ By default the
urlparsemodule, but may be replaced by any object that implementsurlparse.urlparse()andurlparse.urlunparse().
Messages
-
bad_format¶ Emitted for an unparseable URL.
-
blocked_scheme¶ Emitted if the URL
scheme:is not present inallowed_schemes.
-
blocked_part¶ Emitted if the URL has a component not present in
allowed_parts.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
-
class
HTTPURLValidator(**kw)¶ Bases:
flatland.validation.base.ValidatorValidates
httpandhttpsURLs.Validates that an
http-like URL is well-formed and may optionally require and restrict the permissible values of its components.Attributes
-
all_parts¶ A sequence of known URL parts. Defaults to the full 10-tuple of names in
urlparse’s vocabulary for HTTP-like URLs.
-
required_parts¶ A mapping of part names. If value is True, the part is required. The value may also be a sequence of strings; the value of the part must be present in this collection to validate.
The default requires a
schemeof'http'or'https'.
-
forbidden_parts¶ A mapping of part names. If value is True, the part is forbidden and validation fails. The value may also be a sequence of strings; the value of the part must not be present in this collection to validate.
The default forbids
usernameandpasswordparts.
-
urlparse¶ By default the
urlparsemodule, but may be replaced by any object that implementsurlparse.urlparse()andurlparse.urlunparse().
Messages
-
bad_format¶ Emitted for an unparseable URL.
-
required_part¶ Emitted if URL is missing a part present in
required_parts.
-
forbidden_part¶ Emitted if URL contains a part present in
forbidden_parts.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -
-
class
URLCanonicalizer(**kw)¶ Bases:
flatland.validation.base.ValidatorA URL canonicalizing validator.
Given a valid URL, re-writes it with unwanted parts removed. The default implementation drops the
#fragmentfrom the URL, if present.Attributes
-
discard_parts¶ A sequence of 0 or more part names in
urlparse’s vocabulary:'scheme', 'netloc', 'path', 'params', 'query', 'fragment'
-
urlparse¶ By default the
urlparsemodule, but may be replaced by any object that implementsurlparse.urlparse()andurlparse.urlunparse().
Messages
-
bad_format¶ Emitted for an unparseable URL. This is impossible to hit with the Python’s standard library implementation of urlparse.
Construct a validator.
Parameters: **kw – override any extant class attribute on this instance. -