【发布时间】:2021-11-07 01:24:27
【问题描述】:
我在下面的链接中看到了这种用于创建自定义验证器的方法,并希望使用相同的样式,但希望应用验证器 2 字段并要求字段 1 或字段 2 不能为空。我可以使用另一种方法,但如果可能的话,这似乎是最适合这项工作的方法。 Custom validators in WTForms using Flask
【问题讨论】:
标签: python flask wtforms customvalidator
我在下面的链接中看到了这种用于创建自定义验证器的方法,并希望使用相同的样式,但希望应用验证器 2 字段并要求字段 1 或字段 2 不能为空。我可以使用另一种方法,但如果可能的话,这似乎是最适合这项工作的方法。 Custom validators in WTForms using Flask
【问题讨论】:
标签: python flask wtforms customvalidator
一个简单的解决方案是编写一个函数来检查两个字段的输入。
from wtforms.validators import ValidationError
from wtforms.compat import string_types
def validate_one_required(form, field):
if (not form.field_1.data or \
isinstance(form.field_1.data, string_types) and \
not form.field_1.data.strip()) and \
(not form.field_2.data or \
isinstance(form.field_1.data, string_types) and \
not form.field_1.data.strip()):
raise ValidationError('One field is required.')
一个更高级的变体是编写一个验证两个输入的类。
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import ValidationError
from wtforms.compat import string_types
class OneRequired(object):
def __init__(self, fieldname, message=None):
self.fieldname = fieldname
self.message = message
def __call__(self, form, field):
try:
other = form[self.fieldname]
except KeyError:
raise ValidationError(field.gettext("Invalid field name '%s'.") % self.fieldname)
if (not field.data or isinstance(field.data, string_types) and not field.data.strip()) \
and (not other.data or isinstance(other.data, string_types) and not other.data.strip()):
d = {
'other_label': hasattr(other, 'label') and other.label.text or self.fieldname,
'other_name': self.fieldname
}
message = self.message
if message is None:
message = field.gettext('This field or %(other_name)s is required.')
raise ValidationError(message % d)
class MyForm(FlaskForm):
field_1 = StringField('Field 1',
validators=[
OneRequired('field_2')
]
)
field_2 = StringField('Field 2',
validators=[
OneRequired('field_1')
]
)
根据您的要求,您可以选择。
【讨论】: