How to make a field conditionally optional in WTForms?

前端 未结 3 939
渐次进展
渐次进展 2020-12-02 09:46

My form validation is working nearly complete, I just have 2 cases I don\'t know exactly how to solve: 1) The password field should be required of course but I also provide

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 10:02

    I'm not sure this quite fits your needs, but I've used a RequiredIf custom validator on fields before, which makes a field required if another field has a value in the form... for instance, in a datetime-and-timezone scenario, I can make the timezone field required to have a value if the user has entered a datetime.

    class RequiredIf(Required):
        # a validator which makes a field required if
        # another field is set and has a truthy value
    
        def __init__(self, other_field_name, *args, **kwargs):
            self.other_field_name = other_field_name
            super(RequiredIf, self).__init__(*args, **kwargs)
    
        def __call__(self, form, field):
            other_field = form._fields.get(self.other_field_name)
            if other_field is None:
                raise Exception('no field named "%s" in form' % self.other_field_name)
            if bool(other_field.data):
                super(RequiredIf, self).__call__(form, field)
    

    The constructor takes the name of the other field that triggers making this field required, like:

    class DateTimeForm(Form):
        datetime = TextField()
        timezone = SelectField(choices=..., validators=[RequiredIf('datetime')])
    

    This could be a good starting point for implementing the sort of logic you need.

提交回复
热议问题