Skip to content

v0.4.1 -- Conditional Validators and Sphinx Docs

Compare
Choose a tag to compare
@mansam mansam released this 25 Jan 04:44
· 45 commits to master since this release

This release added conditional validators. In some cases you might want to apply some rules only if other validations pass. You can do that with the If(validator, Then(validation)) construct that validator.py provides. For example, you might want to ensure that pet['name'] is a cat’s name, but only if pet['type'] == 'cat'. To do this, you’d use the If validator on the key that serves as the condition for the other set of the rules.

pet = {
    "name": "whiskers",
    "type": "cat"
}
cat_name_rules = {
    "name": [In(["whiskers", "fuzzy", "tiger"])]
}
dog_name_rules = {
    "name": [In(["spot", "ace", "bandit"])]
}
validation = {
    "type": [
        If(Equals("cat"), Then(cat_name_rules)),
        If(Equals("dog"), Then(dog_name_rules))
    ]
}

>>> validate(validation, pet)
(True, {})
# Success!

A failed conditional validation will give you appropriately nested error messages so you know exactly where things went wrong.

pet = {"type":"cat", "name": "lily"}
>>> validate(validation, pet)
(False, {'type': [{'name': ["must be one of ['whiskers', 'fuzzy', 'tiger']"]}]})