Last active
March 13, 2022 00:13
-
-
Save devxoul/7638142 to your computer and use it in GitHub Desktop.
WTForms `RequiredIf` 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
class RequiredIf(object): | |
"""Validates field conditionally. | |
Usage:: | |
login_method = StringField('', [AnyOf(['email', 'facebook'])]) | |
email = StringField('', [RequiredIf(login_method='email')]) | |
password = StringField('', [RequiredIf(login_method='email')]) | |
facebook_token = StringField('', [RequiredIf(login_method='facebook')]) | |
""" | |
def __init__(self, *args, **kwargs): | |
self.conditions = kwargs | |
def __call__(self, form, field): | |
for name, data in self.conditions.iteritems(): | |
if name not in form._fields: | |
Optional(form, field) | |
else: | |
condition_field = form._fields.get(name) | |
if condition_field.data == data and not field.data: | |
Required()(form, field) | |
Optional()(form, field) |
@mcelhenny, how to support FieldList(FormField()
fields? Basically importing a different form from another class. Die form[name]
part breaks as the name
field is unknown.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My version, based on some examples...basically the same thing....also follows same 'usage' as this one