Solution
from enum import Enum, unique
from flask import (
Flask,
redirect,
render_template,
request,
url_for
)
from flask_wtf import FlaskForm
from wtforms import SelectField, StringField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.secret_key = b'your secret here'
# Options for the select box.
@unique
class Options(str, Enum):
OPTION1 = 'Option 1'
OPTION2 = 'Option 2'
OPTION3 = 'Other'
# Validate input based on value and name of another field.
class RequiredIf(DataRequired):
def __init__(self, other_field_name, other_field_value, message=None, *args, **kwargs):
self.other_field_name = other_field_name
self.other_field_value = other_field_value
self.message = message
def __call__(self, form, field):
other_field = form[self.other_field_name]
if other_field is None:
raise Exception(f'no field named "{self.other_field_name}" in form')
if other_field.data == self.other_field_value:
super(RequiredIf, self).__call__(form, field)
class ExampleForm(FlaskForm):
options = SelectField('Options', choices=[e.value for e in Options])
options_details = StringField('Details',
validators=[
RequiredIf('options', Options.OPTION3.value)
]
)
@app.route('/', methods=['GET', 'POST'])
def index():
form = ExampleForm(request.form)
if form.validate_on_submit():
option = form.options.data
if option == Options.OPTION3.value:
option = form.options_details.data
print(option)
return redirect(url_for('index'))
return render_template('index.html', **locals())