Validators¶
The last step in cooked input is to validate that the entered input is valid. When called, Validators return True if the input passes the validation (i.e. is valid), and False otherwise.
Creating Validators¶
Validator classes inherit from the Validator
base class. They must be a callable, and take three parameters:
the value
to validate, a function to call when an error occurs and a format string
for the error function. See error callbacks for more information on error functions and their
format strings.
An example of a validator to verify that the input is exactly a specified length looks like:
class LengthValidator(Validator):
def __init__(self, min_len=None, max_len=None):
self._min_len = min_len
self._max_len = max_len
def __call__(self, value, error_callback, validator_fmt_str):
try:
val_len = len(value)
except (TypeError):
print('LengthValidator: value "{}" does not support __len__.'.format(value), file=sys.stderr)
return False
min_condition = (self._min_len is None or val_len >= self._min_len)
max_condition = (self._max_len is None or val_len <= self._max_len)
if min_condition and max_condition:
return True
elif not min_condition:
error_callback(validator_fmt_str, value, 'too short (min_len={})'.format(self._min_len))
return False
else:
error_callback(validator_fmt_str, value, 'too long (max_len={})'.format(self._max_len))
return False
Note
There are a large number of Boolean validation functions available from the validus
project. These can be used as cooked_input validation functions by wrapping them in a SimpleValidator
. For
instance, to use validus
to validate an email address:
from validus import isemail
email_validator = SimpleValidator(isemail, name='email')
email = get_input(prompt='enter a valid Email address', validators=email_validator)
Validators¶
AnyOfValidator¶
-
class
cooked_input.
AnyOfValidator
(validators)¶ check if a value matches any of a set of validators (OR operation).
Parameters: validators (List[Validator]) – a list of validators. Returns True once any of the validators passes.
Returns: True if the input passed validation, else False Return type: boolean Note
if
choices
is mutable, it can be changed after the instance is created.Example:
rv1 = RangeValidator(min_val=1, max_val=3) rv2 = EqualToValidator(7) nv = AnyOfValidator([rv1, rv2]) prompt_str = "Enter a number (between 1 and 3, or 7)" result = get_int(prompt=prompt_str, validators = nv)
ChoiceValidator¶
-
class
cooked_input.
ChoiceValidator
(choices)¶ check if a value is in a set of choices.
Parameters: choices (Iterable) – an iterable (tuple, list, or set) containing the allowed set of choices for the value. Returns: True if the input passed validation, else False Return type: boolean Example:
colors = ["red", "green", "blue"] cv = ChoiceValidator(colors] result = get_string(prompt="Enter a color", validators=cv)
EqualToValidator¶
-
class
cooked_input.
EqualToValidator
(value)¶ check if a value is equal to a specified value.
Parameters: value (Any) – the value to match Returns: True if the input passed validation, else False Return type: boolean
IsFileValidator¶
-
class
cooked_input.
IsFileValidator
¶ check is a string is the name of an existing filename
Parameters: value (str) – the filename to verify Returns: True if the input passed validation, else False Return type: boolean
LengthValidator¶
-
class
cooked_input.
LengthValidator
(min_len=None, max_len=None)¶ check the length of a value is in a range (open interval). For exact length match set
min_len
andmax_len
lengths to the same value.Parameters: - min_len (int) – the minimum required length for the input. If None (default), no minimum length is checked.
- max_len (int) – the maximum required length for the input. If None (default), no maximum length is checked.
Returns: True if the input passed validation
Return type: boolean
Example:
lv = LengthValidator(min_len=3, max_len=5) result = get_string(prompt="Enter a 3 to 5 char string", validators=lv)
ListValidator¶
-
class
cooked_input.
ListValidator
(len_validators=None, elem_validators=None, len_validator_fmt_str=None)¶ Run a set of validators on a list.
Parameters: - len_validators (List[Validator]) –
a list of validators to run on the length of the
value
list. if None (default) no validation is done on the list length. - elem_validators (List[Validator]) –
a list of validators to apply to the elements of the list.
- len_validator_fmt_str (str) – a format string to use as an error message is the length of the
value
string does not pass the length validation (len_validators
). If None (default),validator_fmt_str
is used from the call to the validator.
Returns: True if the input passed validation, else False
Return type: boolean
Note
len_validators
is usually an instance ofEqualToValidator
for a list of a specific length, orRangeValidator
for a list whose length is in a range.LengthValidator
is not used as thevalue
passed to the validator is the length of the list, not the list itself.Example:
colors = ['red', 'green', 'blue'] len_validator = ci.RangeValidator(min_val=2, max_val=4) lvfs="List length {error_content} ({value})" elem_validator = ci.ChoiceValidator(colors) prompt_str = "Enter a list of 2 to 4 colors" lv = ci.ListValidator(len_validators=len_validator, elem_validators=elem_validator, len_validator_fmt_str=lvfs) result = ci.get_list(prompt=prompt_str, validators=lv)
- len_validators (List[Validator]) –
NoneOfValidator¶
-
class
cooked_input.
NoneOfValidator
(validators)¶ check if a value does not pass validation for a list of validators (NOT operation).
Parameters: validators (List[Validator]) – a list of validators that should not pass validation on the input value
Returns: True if the input passed validation, else False Return type: boolean Note
if
choices
is mutable, it can be changed after the instance is created.Example:
rv1 = RangeValidator(min_val=1, max_val=3) rv2 = EqualToValidator(7) nv = NoneOfValidator([rv1, rv2]) prompt_str = "Enter a number (not between 1 and 3, and not 7)" result = get_int(prompt=prompt_str, validators = nv)
PasswordValidator¶
-
class
cooked_input.
PasswordValidator
(min_len=None, max_len=None, min_lower=0, min_upper=0, min_digits=0, min_puncts=0, allowed=None, disallowed=None)¶ validate a password string.
Parameters: - min_len (int) – the minimum allowed password length (default=1)
- max_len (int) – the maximum password length (default=64)
- min_lower (int) – the minimum number of lower case letters (default=``None``)
- min_upper (int) – the minimum number of upper case letters (default=``None``)
- min_digits (int) – the minimum number of digits (default=``None``)
- min_puncts (int) – the minimum number of punctuation characters (default=``None`)
- allowed (str) – a string containing the allowed characters in the password. Default is upper and lower case ascii letters, plus digits, plus punctuation characters
- disallowed (str) – a string containing characters not allowed in the password (default=``None``)
Returns: True if the input passed validation, else False
Return type: boolean
Example:
pv = PasswordValidator(min_len=5, min_lower=2, min_upper=2, min_digits=1, min_puncts=1) result = ci.get_string(prompt="Enter a password", validators=pv, hidden=True)
RangeValidator¶
-
class
cooked_input.
RangeValidator
(min_val=None, max_val=None)¶ check if a value is in a specified range (open interval.) The value can be of any type as long as the
__ge__
and__le__
comparison functions are defined.Parameters: - min_val (Any) – The minimum allowed value (i.e.
value
must be >=min_val
). If None (the default), no minimum value is checked. - max_val (Any) – The maximum allowed value (i.e.
value
must be <= max_val). If None (the default), no maximum value is checked.
Returns: True if the input passed validation, else False
Return type: boolean
Example:
rv = RangeValidator(min_val=1), max_val=10) result = get_int(prompt="Enter a number (1 to 10)", validators=rv)
- min_val (Any) – The minimum allowed value (i.e.
RegexValidator¶
-
class
cooked_input.
RegexValidator
(pattern, regex_desc=None)¶ check if a value matches a regular expression.
Parameters: - pattern (str) –
the regular expression to match
- regex_desc (str) – a human readable string to use for the regular expression (used for error messages)
Returns: True if the input passed validation, else False
Return type: boolean
Example:
rv = RegexValidator(pattern=r'^[2-9]\d{9}$', regex_desc='phone number') result = get_string(prompt="Enter a phone number", validators = rv)
- pattern (str) –
SimpleValidator¶
-
class
cooked_input.
SimpleValidator
(validator_func, name='SimpleValidator value')¶ use a simple function as a validator.
validator_func
is any callable that takes a single value as input and returns True if the value passes (and False otherwise.) Used to wrap functions (e.g. validus functions. Can also be used with func.partial to wrap validation functions that take more complex parameters.Parameters: - validator_func (Callable) – a function (or other callable) called to validate the value
- name (str) – an optional string to use for the validator name in error messages
Returns: True if the input passed validation, else False
Return type: boolean
Example:
def is_even(value): return True if (value % 2) == 0 else False sv = SimpleValidator(is_even, "EvenNumberValidator") result = get_int(prompt="Enter an even number", validators = sv)