N elements list of string validation in cerberus

Viewed 1063

How can I validate that certain type is a list and it contains only e.g string elements, of unknown number?

My current solution is

'categories_id' : {'required' : False, 'type' : ['string','list']},

but it doesn't do the trick, is also returns True when you supply just a single string, not in a list.

2 Answers

The schema mentioned in the question 'categories_id' : {'required' : False, 'type' : ['string','list']} makes Cerberus check categories_id field is either a string or a list. So a single string will return true.

To make Cerberus check that categories_id is a list of strings with any number of items, following schema should be used

{'categories_id': {'required': False, 'type': 'list', 'schema': {'type': 'string'}}}

I haven't found a way to do that using cerberus, but it should be pretty simple without any modules:

def validate(l):
    if isinstance(l, list):
        return all(isinstance(I, str) for i in l)
Related