Skip to content

Instantly share code, notes, and snippets.

@shimizukawa
Created April 28, 2014 00:18
Show Gist options
  • Save shimizukawa/11358819 to your computer and use it in GitHub Desktop.
Save shimizukawa/11358819 to your computer and use it in GitHub Desktop.
colander validation with related two fields combination. see also: http://docs.pylonsproject.org/projects/colander/en/latest/extending.html#defining-a-new-validator
from colander import MappingSchema, SchemaNode, String, Invalid
import string
def combined_validator(node, value):
if value.get('name') != value.get('value'):
raise Invalid(node, 'name and value must be identical. {!r}'.format(value))
class Schema1(MappingSchema):
name = SchemaNode(String(), preparer=string.lower)
value = SchemaNode(String(), preparer=string.lower)
# validator can be specified as a argument.
schema1 = Schema1(validator=combined_validator)
schema1.deserialize({'name': 'Spam', 'value': 'spam'})
#=> no error
schema1.deserialize({'name': 'Spam', 'value': 'Egg'})
#=>raise: Invalid: {'': "name and value must be identical. {'name': u'spam', 'value': u'egg'}"}
# validator also can be implemented as a schema's method.
class Schema2(Schema1):
def validator(self, node, value):
return combined_validator(node, value)
schema2 = Schema2()
schema2.deserialize({'name': 'Spam', 'value': 'spam'})
#=> no error
schema2.deserialize({'name': 'Spam', 'value': 'Egg'})
#=>raise: Invalid: {'': "name and value must be identical. {'name': u'spam', 'value': u'egg'}"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment