Skip to content

Instantly share code, notes, and snippets.

@sc0tt
Last active January 25, 2016 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sc0tt/27737efb1813121f2c05 to your computer and use it in GitHub Desktop.
Save sc0tt/27737efb1813121f2c05 to your computer and use it in GitHub Desktop.
Converts a WTForms form to JSON which http://formvalidation.io/ accepts. May become a library in the future.
from wtforms.validators import DataRequired, Length, Email, UUID, MacAddress, EqualTo, Regexp
def convert_form_to_json(form):
def convert_field_to_json(field):
validations = {}
for val in field.validators:
validation_type = val.__class__
if validation_type not in validation_types:
raise Exception('Unknown validator')
validations[validation_types[validation_type]['type']] = {}
for (argKey, argVal) in validation_types[validation_type]['attributes'].items():
try:
if argKey == "regex":
attr = getattr(val, argKey).pattern
else:
attr = getattr(val, argKey)
validations[validation_types[validation_type]['type']][argVal] = attr
except AttributeError:
raise
return validations
validation_types = {DataRequired: {'type': 'notEmpty', 'attributes': {'message': 'message'}},
Length: {'type': 'stringLength',
'attributes': {'min': 'min', 'max': 'max', 'message': 'message'}},
Email: {'type': 'emailAddress', 'attributes': {'message': 'message'}},
UUID: {'type': 'uuid', 'attributes': {'message': 'message'}},
MacAddress: {'type': 'mac', 'attributes': {'message': 'message'}},
EqualTo: {'type': 'identical', 'attributes': {'message': 'message', 'fieldname': 'field'}},
Regexp: {'type': 'regexp', 'attributes': {'message': 'message', 'regex': 'regexp'}}}
output = {}
for field in form:
if not field.validators:
continue
output[field.name] = {'validators': convert_field_to_json(field)}
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment