How to make a field conditionally optional in WTForms?

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

    The answer from @dcrosta is great, but I think some things have changed in wtforms since this answer. Inheriting from DataRequired adds a required attribute to the form field, so the conditional validator never gets called. I made a minor change to the class from @dcrosta that works with wtforms 2.1. This only over-rides field_flags so that browser validation is not done.

    from wtforms.validators import DataRequired
    
    
    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
    
        """
        field_flags = ('requiredif',)
    
        def __init__(self, other_field_name, message=None, *args, **kwargs):
            self.other_field_name = other_field_name
            self.message = message
    
        def __call__(self, form, field):
            other_field = form[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)
    

    A more ideal solution would manage to do the validation in the browser, like the current behavior of DataRequired.

提交回复
热议问题