Created
July 20, 2018 05:25
-
-
Save the-vampiire/9eebf2c3fb92421041869bd6804d7ca5 to your computer and use it in GitHub Desktop.
form validation (function and class examples)
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
| def validate_name_as_caps(name): | |
| """ | |
| raise ValueError and pass respective message | |
| """ | |
| if name.upper() != name: | |
| raise ValueError("Name is not capitalized") | |
| return name | |
| validators = { | |
| 'name': validate_name_as_caps | |
| } | |
| def validate_form(form, validators): | |
| output = { | |
| 'valid': {}, | |
| 'errors': {}, | |
| 'skipped': [] # stores fields that have no corresponding validator function | |
| } | |
| for field, val in form.items(): | |
| try: | |
| if field in validators: | |
| output['valid'][field] = validators[field](val) | |
| else: | |
| output['valid'][field] = val | |
| output['skipped'].append(field) | |
| except ValueError as error: | |
| output['errors'][field] = str(error) | |
| return output | |
| good_form = { | |
| 'name': 'UPPERCASE', | |
| 'skipped': 'no validator' | |
| } | |
| bad_form = { | |
| 'name': 'lowercase', | |
| 'skipped': 'no validator' | |
| } | |
| good_output = validate_form(good_form, validators) | |
| bad_output = validate_form(bad_form, validators) | |
| print('good output:', good_output) | |
| print('bad output:', bad_output, '\n') | |
| """ | |
| or as a class | |
| """ | |
| class FormValidator: | |
| """ | |
| pass a validators dictionary with validation functions | |
| """ | |
| def __init__(self, validators): | |
| self.validators = validators | |
| self.valid = {} | |
| self.errors = {} | |
| self.skipped = [] # for fields that have no validator | |
| def validate(self, form): | |
| for field, val in form.items(): | |
| try: | |
| if field in self.validators: | |
| self.valid[field] = self.validators[field](val) | |
| else: | |
| self.valid[field] = val | |
| self.skipped.append(field) | |
| except ValueError as error: | |
| self.errors[field] = str(error) | |
| good_validator = FormValidator(validators) | |
| good_validator.validate(good_form) | |
| print(f'good values: {good_validator.valid}\n\ | |
| good errors: {good_validator.errors}\n\ | |
| skipped fields: {good_validator.skipped}\n') | |
| bad_validator = FormValidator(validators) | |
| bad_validator.validate(bad_form) | |
| print(f'bad values: {bad_validator.valid}\n\ | |
| bad errors: {bad_validator.errors}\n\ | |
| skipped fields: {good_validator.skipped}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment