Skip to content

Instantly share code, notes, and snippets.

@andrewnimmo
Forked from devxoul/wtf_required_if.py
Created March 13, 2022 00:13
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 andrewnimmo/f1cbabee6980e5c6e50f3a69cca530a4 to your computer and use it in GitHub Desktop.
Save andrewnimmo/f1cbabee6980e5c6e50f3a69cca530a4 to your computer and use it in GitHub Desktop.
WTForms `RequiredIf` validator.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment