Only applying WTForms validations if another field has a specific value

When you have a WTForms field that have a radio button that can change between different field types, you might want to only apply certain validators if the field has a specific value (for example to swap between types of users, types of cars, etc.).

This is a custom validator that stops validation if a specific field doesn’t have the assumed value – and can also require the field to be present (so that the field can’t just be left empty even if the other field is present).

def validator_required_if(other_field_name, other_value, is_required: bool = False):
    def _validator(form, field):
        other_field = form[other_field_name]

        if other_field.data == other_value:
            if not field.data or (isinstance(field.data, str) and not field.data.strip()):
                raise StopValidation(f'This field is required when {other_field.label.text} is "{other_value}"')
        else:
            field.data = None

            if not is_required:
                field.errors[:] = []

            raise StopValidation()

    return _validator

Usage of the validator in a WTForms field:

# 'type' is a different field on the same form.
# 'label' is the value 'type' should have to apply the following validators
text = StringField(_l('Label'), validators=[validator_required_if('type', 'label'), InputRequired()])

The example verifies that the field text has input present if the field type is set to label. If the field type is set to label but text isn’t present, an error will be thrown.