Created
August 26, 2015 22:40
-
-
Save jchysk/1d886d644afd73a75132 to your computer and use it in GitHub Desktop.
Formencode validator that will require a minimum of one field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from formencode import Schema, validators, Invalid | |
from formencode.validators import FormValidator | |
class RequireAtLeastOne(FormValidator): | |
choices = [] | |
__unpackargs__ = ('choices',) | |
def _convert_to_python(self, value_dict, state): | |
for each in self.choices: | |
if value_dict.get(each) is not None: | |
return value_dict | |
raise Invalid('You must give a value for %s' % repr(self.choices), value_dict, state) | |
class ValidateThings(Schema): | |
field1 = validators.String(if_missing=None) | |
field2 = validators.String(if_missing=None) | |
field3 = validators.String(if_missing=None) | |
chained_validators = [RequireAtLeastOne(['field1', 'field2', 'field3'])] | |
""" Success """ | |
params = ValidateThings().to_python({"field2": 12}) | |
params = ValidateThings().to_python({"field2": 12, "field3": 126}) | |
params = ValidateThings().to_python({"field1": "foo", "field2": 12, "field3": 126}) | |
""" Failure """ | |
params = ValidateThings().to_python({}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment