Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aaronlelevier opened this issue Aug 12, 2019 · 1 comment
Labels

Comments

@aaronlelevier
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants