typesystem icon indicating copy to clipboard operation
typesystem copied to clipboard

fields.Choice to include list of choices in validation error message

Open aaronlelevier opened this issue 6 years ago • 1 comments

Would it be possible for the Choice class to include a list of acceptable choices in the validation error output?

Here is a snippet doing this using subclassing.

import typesystem

class MyChoice(typesystem.fields.Choice):
    
    def __init__(self, *, choices=None, **kwargs):
        super().__init__(choices=choices, **kwargs)
        self.single_choices = [x[0] for x in self.choices]
        self.errors["choice"] = "Not a valid choice. Please choose: {single_choices}"
    
field = MyChoice(choices=[('foo', 'foo')])

field.validate('bar')

This will raise the following error message (this is an ipython notebook error message, but hopefully demonstrates ok):

---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
<ipython-input-65-854f15494f03> in <module>
      8 field = MyChoice(choices=[('foo', 'foo')])
      9 
---> 10 field.validate('bar')

~/Documents/entanglement/venv/lib/python3.7/site-packages/typesystem/fields.py in validate(self, value, strict)
    384                     return None
    385                 raise self.validation_error("required")
--> 386             raise self.validation_error("choice")
    387         return value
    388 

ValidationError: Not a valid choice. Please choose: ['foo']

aaronlelevier avatar Aug 12 '19 22:08 aaronlelevier

bump, hey, haven't heard back. If the request is invalid, please lmk. I'd be happy to submit a PR for the functionality if you think it's worth it. Thanks

aaronlelevier avatar Aug 20 '19 14:08 aaronlelevier