Search code examples
pythonjsonpython-3.xcerberus

How to prohibit certain words in a json value with cerberus


Lets say that I have this json:

{"name": "John"}

And I want to restrict the json from containing the substring "my name is", so if I receive:

{"name": "my name is John"}

Cerberus will me that the json is not correct and I can display the correct output, so far I have tried the "forbidden" field but it does not work, because forbidden only takes the exact phrase, this is how I have so far the cerberus validation:

{
  "name":{
    "type": "string",
    "minlength":1,
    "forbidden":["my name is"],
  }
}

Thanks!


Solution

  • Looks like you will want to use check_with alongside a simple function to forbid what you want to exclude e.g.

    def cleanName(field, value, error):
        if 'my name is' in value:
            error(field, 'error message')