cerberus: Problem with required and dependencies

Used Cerberus version 1.0.1 installed with pip

Support request / Bug report

According to the docs, the following program should validate successfully since the auth-key field is required only when the auth field is wep or wpa.


import cerberus

schema = {
    'auth' : {
        'type':'string',
        'required':True,
        'allowed':['open','wep','wpa']
    },
    'auth-key' : {
        'type':'string',
        'required':True,
        'dependencies': {'auth': ['wep', 'wpa']}
    }
}

v = cerberus.Validator(schema)
print v.validate({'auth':'open'})
print v.errors

The output of the program is the following:

False
{'auth-key': ['required field']}

Is this a bug ?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 16 (3 by maintainers)

Commits related to this issue

Most upvoted comments

I’ll add my two cents since I’m the one who opened the issue. I think that obvious things should just work, without complicated hacks that make the rules obscure and hard to understand. Before opening this issue i’ve read the docs many times and spent almost an hour trying to understand why it didn’t work. In the end I realized that I was fighting against the library instead of using it to solve my problem, so I gave up and coded the validation logic by hand.

To avoid confusion I’ll post here the relevant lines extracted from the documentation of the “required” validation option:

Note String fields with empty values will still be validated, even when required is set to True. If you don’t want to accept empty values, see the empty rule. Also, if dependencies are declared for the field, its required rule will only be validated if all dependencies are included with the document.

I am no english expert… but what I think when I see this phrase in the docs is that a required field is NOT required if the dependencies of that field are missing. In other words, I’m not required to tell you my wireless password if I’m going with open authentication.

I think that such a rule is actually very common in validation, so common that it should be pretty straightforward to implement and work out of the box without obscure hacks.

From what I see here there is either a false statement in the docs or a bug in the code. If fixing the code is not possible due to backwards compatibility then fix the docs.

IMHO, adding some weird non-intuitive rules to make it work is a bad idea.

I don’t think it’s a bug. You need to be more precise when specifying the auth-key:

schema = {
    'auth' : {
        'type':'string',
        'required':True,
        'allowed':['open','wep','wpa']
    },
    'auth-key' : {
        'type':'string',
        'oneof': [{
            'required':True,
        }, {
            'dependencies': {'auth': ['open']},
        }]
    }
}

It’s like saying: “wether auth-key is defined or auth is ‘open’”.