Created
April 28, 2014 00:18
-
-
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
This file contains hidden or 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 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