Search code examples
pythonvalidationcerberus

cerberus: forbid field existance


I want to use Cerberus to validate that a field is NOT present in the object.

I would like to use something like:

my_schema = {
    'normal_field': {
        'type': 'string',
    },
    'forbidden_field': {
        'forbid': True,
    },
}

Basically, I would like to never accept an object that comes with the forbidden_field. Right now I am accepting changing my validator with:

validator.allow_unknown = False

Which basically does the trick on setting a schema with only "allowed" fields, but I don't really like what it does, as this forbids me to accept other fields, not only the forbidden_field.

I also saw the allowed and forbidden validation rules, but they check the value of the field, not really the existence of the field.

So, how could I tell my validator to only forbid specific field existence with Cerberus?


Solution

  • I fixed this problem with the readonly rule which also allowed me to set a default_setter value.

    @kchan's answer works for not allowing the field, but it breaks normalization integration (trying to use it with default_setter for example).