Skip to content

Instantly share code, notes, and snippets.

@devxoul
Last active March 13, 2022 00:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devxoul/7638142 to your computer and use it in GitHub Desktop.
Save devxoul/7638142 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)
@JiDai
Copy link

JiDai commented Oct 21, 2015

Miss import Optional and Required ?

@mcelhennyi
Copy link

mcelhennyi commented May 26, 2018

from wtforms.validators import DataRequired, Optional


class RequiredIf(DataRequired):
    """Validator which makes a field required if another field is set and has a truthy value.

    Sources:
        - http://wtforms.simplecodes.com/docs/1.0.1/validators.html
        - http://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms
        - https://gist.github.com/devxoul/7638142#file-wtf_required_if-py
    """
    field_flags = ('requiredif',)

    def __init__(self, message=None, *args, **kwargs):
        super(RequiredIf).__init__()
        self.message = message
        self.conditions = kwargs

    # field is requiring that name field in the form is data value in the form
    def __call__(self, form, field):
        for name, data in self.conditions.items():
            other_field = form[name]
            if other_field is None:
                raise Exception('no field named "%s" in form' % name)
            if other_field.data == data and not field.data:
                DataRequired.__call__(self, form, field)
            Optional()(form, field)

My version, based on some examples...basically the same thing....also follows same 'usage' as this one

@tvb
Copy link

tvb commented Jun 16, 2020

@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