简体   繁体   中英

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM