我如何验证wtforms字段彼此? [英] How do I validate wtforms fields against one another?
本文介绍了我如何验证wtforms字段彼此?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在表单中有三个相同的 SelectField
输入,每个都有相同的选项集。我不能使用一个多选。
我想确保用户为这三个字段选择三个不同的选择。
在自定义验证中,似乎一次只能引用一个字段,而不会将此字段的值与其他字段进行比较。我怎样才能做到这一点?谢谢!
解决方案您可以在<$ c $中覆盖
validate
c> Form ... class MyForm(Form):
select1 = SelectField ('Select 1',...)
select2 = SelectField('Select 2',...)
select3 = SelectField('Select 3',...)
def validate (self):
如果不是Form.validate(self):
return False
result = True
seen = set()
在[self.select1 ,self.select2,self.select3]:
如果看到field.data:
field.errors.append('请选择三个不同的选项')
result = False
else:
seen.add(field.data)
返回结果
I have three identical SelectField
inputs in a form, each with the same set of options. I can't use one multiple select.
I want to make sure that the user selects three different choices for these three fields.
In custom validation, it appears that you can only reference one field at a time, not compare the value of this field to others. How can I do that? Thanks!
解决方案
You can override validate
in your Form
...
class MyForm(Form):
select1 = SelectField('Select 1', ...)
select2 = SelectField('Select 2', ...)
select3 = SelectField('Select 3', ...)
def validate(self):
if not Form.validate(self):
return False
result = True
seen = set()
for field in [self.select1, self.select2, self.select3]:
if field.data in seen:
field.errors.append('Please select three distinct choices.')
result = False
else:
seen.add(field.data)
return result
这篇关于我如何验证wtforms字段彼此?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文