Search code examples
pythonjsonpython-3.xvalidationcerberus

Dependencies validation based on conditions using Cerberus


There are two fields "field1" and "field2". The condition is either "field1" or "field2" can take 'ANY' value, but both fields cannot have 'ANY' value. How to add either dependencies or oneof or excludes based on the above condition?


from cerberus import Validator
v = Validator()

document = {
    "field1": "ANY",
    "field2": "ANY",
    "field3": "ANY" # This field can be ANY
}

schema = {
    "field1": {"required": True},
    "field2": {"required": True, "dependencies": {"field1": ["ANY"]},}, # I want this condition to be like "field2"shouldn´t be "ANY" if "field1" is  "ANY" and vice-versa.
}

v.validate(document, schema)  
print(v.errors)


Solution

  • I made below changes in the schema and it works fine.

    
    from cerberus import Validator
    v = Validator()
    
    document = {
        "field1": "ANY",
        "field2": "ANY",
        "field3": "ANY" # This field can be ANY
    }
    
    schema = {
        "field1": {"required": True, "noneof": [{"allowed": ["ANY"], "dependencies": {"field2": ["ANY"]}},]},
        "field2": {"required": True, "noneof": [{"allowed": ["ANY"], "dependencies": {"field1": ["ANY"]}},]}, 
    }
    
    v.validate(document, schema)  
    print(v.errors)