Flask:在多个表单字段上进行条件验证 [英] Flask: conditional validation on multiple form fields
问题描述
让我从平常开始-我对Python&烧瓶.在发布这个问题(这是我的第一个问题)之前,我花了很多时间进行搜索和试验,但到目前为止还没有运气.
Let me start with usual - I'm new to both Python & Flask. Before posting this question (my first ever here) I have spent number of hours searching and experimenting, unfortunately with no luck so far.
我正在构建Web表单,用户可以在其中定义防火墙规则,这些规则随后会记录在数据库中.我正处于验证阶段,在这里碰到了墙...希望有人能够帮助我.
I am building web form where user can define firewall rules, which subsequently get recorded in the database. I am at the validation stage and I came up to a wall here... hopefully someone will be able to help me out.
我的表单(这里简化)有2个字段-src_ip和dst_ip:
My (simplified here) form has 2 fields - src_ip and dst_ip:
class FirewallRule(Form)
src_ip = StringField('Source IP')
dst_ip = StringField('Destination IP')
我的验证要求是:
- 至少必须填写1个字段(两个都可以)
- 填充的字段必须包含有效的IP地址
wtforms.validators.IPAddress()和自定义验证功能似乎是我的朋友,但是我正在努力寻找一种将它们连接在一起的方法.
wtforms.validators.IPAddress() and custom validation function seems to be my friend, but I am struggling to find a way to plug them together.
本质上,我正在尝试建立条件验证:
Essentially I am trying to build conditional validation:
- 如果不是(src_ip或dst_ip);返回False
- 如果src_ip和src_ip无效,则为IP地址;返回False
- 如果dst_ip和dst_ip无效,则为IP地址;返回False
- 返回真实
很明显,我想重用IPAddress()[或通常使用任何内置的验证器],而不是自己编写.
Obviously I would like to re-use IPAddress() [or generally any of the built-in validators] rather then write my own.
我确定有人必须已经做过..很遗憾,我找不到正确方向的任何指针.
I am sure someone must have done it before.. unfortunately I could not find any pointers in the right direction.
谢谢.
推荐答案
您缺少一个非常有用的验证器:可选.该验证器允许您说一个字段可以为空,但如果该字段不为空,则应使用其他验证器.
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.
这篇关于Flask:在多个表单字段上进行条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!