且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flask:在多个表单字段上进行条件验证

更新时间:2023-11-09 20:32:16

您缺少一个非常有用的验证器:可选.该验证器允许您说一个字段可以为空,但如果该字段不为空,则应使用其他验证器.

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.

所以会是这样:

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

如果要避免使用自定义验证功能,请考虑创建一个验证器类来检查是否已设置字段列表中的至少一个是相当容易的.您可以查看 EqualTo 验证器的实现灵感,如果你想走这条路.

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.