1

Python cerberus has a validation rule called meta where I assign a dict to meta rule. How am i supposed to access it? I am writing a custom error_handler using this to customise the error messages.

My target is schema = {'a': {'type': 'integer', 'meta': {'label': 'Age'}}} and would like to use the label in my error message.

Any help would be appreciated.

yugantar
  • 1,970
  • 1
  • 11
  • 17
  • i don't have the time for a detailed answer, but if you want to access the `schema` property of a validator from the error handler, you'll have to bind the validator to some property of the handler first. probably in `_format_message`, you can then resolve to the `meta` rule in the schema with `error.schema_path`. – funky-future Jun 24 '19 at 10:02
  • @yugantar, did you find a way to access the `label` in your error messages? I have a similar situation as seen in [this question](https://stackoverflow.com/q/56936542/1082673) and I can't seem to figure out how to do that – lukik Jul 08 '19 at 19:38
  • Hi @lukik , I have answered my own question and also added an answer to your question of how I got around this use case – yugantar Jul 09 '19 at 10:11

1 Answers1

4

Answering my own question.

I created a custom error_handler to prepend the label to my error messages.

from cerberus.errors import BasicErrorHandler

class CustomErrorHandler(BasicErrorHandler):
    def __init__(self, schema):
        self.custom_defined_schema = schema

    def _format_message(self, field, error):
        return self.custom_defined_schema[field].get('meta', {}).get('label', field) + ': ' + super(CustomErrorHandler, self)._format_message(field, error)

val = Validator(schema, error_handler=CustomErrorHandler(schema))

Hopefully it'll help the future users.

yugantar
  • 1,970
  • 1
  • 11
  • 17