Skip to content

Instantly share code, notes, and snippets.

@inabhi9
Created September 13, 2013 13:47
Show Gist options
  • Save inabhi9/6550950 to your computer and use it in GitHub Desktop.
Save inabhi9/6550950 to your computer and use it in GitHub Desktop.
formencode additional extended validators
from formencode import FancyValidator, Invalid
import dateutil
import formencode
class validators:
class ISODateTime(FancyValidator):
"""
Validate and converts ISO formatted datetime string to python
datetime object
"""
messages = {
'malformed': '%(date)s is not an ISO format.'
}
def _to_python(self, value, state):
return dateutil.parser.parse(value)
# Before conversion by _to_python
def validate_other(self, value, state):
try:
dateutil.parser.parse(value)
except:
raise Invalid(self.message("malformed", state, date=value),
value, state)
class Mixed(FancyValidator):
"""
This validator takes dictionary of key and its validator and perform
validation on each member
Dictionary should be of key - validator only.
.. Note:: Further nesting is not support at the moment
"""
validator_dict = {}
value_dict = {}
def __init__(self, *args, **kw):
self.validator_dict = args[0]
FancyValidator.__init__(self, **kw)
def to_python(self, value, state):
Schema = type('Schema', (formencode.Schema,), self.validator_dict)
return Schema.to_python(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment