Flask: conditional validation on multiple form fields

冷暖自知 提交于 2019-12-01 06:06:01

You are missing one very useful validator: Optional. This validator allows you to say that a field can be empty, but if it isn't empty then other validators should be used.

The part about having at least one of the fields filled out I would do with a custom validation method, I don't think there is any stock validators that can help with that.

So it would be something like this:

class FirewallRule(Form)
    src_ip = StringField('Source IP', validators=[Optional(), IPAddress()])
    dst_ip = StringField('Destination IP', validators=[Optional(), IPAddress()])

    def validate(self):
        if not super(FirewallRule, self).validate():
            return False
        if not self.src_ip.data and not self.dst_ip.data:
            msg = 'At least one of Source and Destination IP must be set'
            self.src_ip.errors.append(msg)
            self.dst_ip.errors.append(msg)
            return False
        return True

If you want to avoid a custom validation function, then consider that it would be fairly easy to create a validator class to check that at least one of a list of fields are set. You can look at the implementation of the EqualTo validator for inspiration if you would like to follow this route.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!