4

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?

eLRuLL
  • 18,488
  • 9
  • 73
  • 99

2 Answers2

2

I seem to recall encountering this particular use case before. You might try the following:

from cerberus import Validator

schema = {
    'foo': {
        'type': 'string',
        'validator': lambda field, value, error: error(field, 'field is forbidden!!'),
    }
}
v = Validator(schema)
v.allow_unknown = True
doc = {
    'foo': 'bar'
}
print(v.validate(doc))

The result should return False and v.errors should say "field is forbidden!!"

see:

kchan
  • 836
  • 8
  • 13
1

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).

eLRuLL
  • 18,488
  • 9
  • 73
  • 99