Last active
January 25, 2016 01:10
-
-
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.
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 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