Detect empty string in numeric field using Cerberus

1.2k Views Asked by At

I am using the python library cerberus (http://docs.python-cerberus.org/en/stable/) and I want to check if a JSON field is a number (integer) or an empty string.

I tried using the condition:

{"empty": True, "type": "intenger"}

But when the field is an empty string, for example: (""), I get the following error.

'must be of integer type'

Is there a way of using the basic validation rules so it detects also an empty string in a numeric field?, I know it can be done by using extended validation functions but I want to avoid that solution for the moment.

2

There are 2 best solutions below

0
On BEST ANSWER

Try something like this:

{"anyof":[
   {"type":"string","allowed":[""]},
   {"anyof_type":["float","integer"]}
]},
0
On

I would advise to not overcomplicate schemas. 1) Multiple types can be declared for the type rule. 2) The empty rule is only applied to sizable values, so it would ignore any given integer. Hence this is the simplest possible rules set for your constraints:

{'type': ('integer', 'string'),
 'empty': True}

Mind that this doesn't enforce the value to be an empty string, but allows it to be, vulgo: a non-empty string would also pass. You may want to use the max_lengh rule w/ 0 as constraint instead.