How to make a field conditionally optional in WTForms?

前端 未结 3 925
渐次进展
渐次进展 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:09

    I found this question helpful and based on the answer of @dcrosta I created another validator which is optional. The benefit is that you can combine it with other wtforms validators. Here is my optional validator which checks another field. Because I needed to check the value of the other field against some certain value I added a custom check for value:

    class OptionalIfFieldEqualTo(wtf.validators.Optional):
        # a validator which makes a field optional if
        # another field has a desired value
    
        def __init__(self, other_field_name, value, *args, **kwargs):
            self.other_field_name = other_field_name
            self.value = value
            super(OptionalIfFieldEqualTo, 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 other_field.data == self.value:
                super(OptionalIfFieldEqualTo, self).__call__(form, field)
    

提交回复
热议问题