class ContactForm(Form):
name = StringField('Name',
validators=[DataRequired(), Length(max=255)])
email = StringField('Email',
validators=[Optional(), Email(), Length(max=255)])
phone = StringField('Phone number',
validators=[Optional(), NumberRange(min=8, max=14)])
comment = TextAreaField(u'Comment',
validators=[DataRequired()])
是否有指定验证程序,以便需要email
或phone
?
答案 0 :(得分:2)
您可以在表单上创建validate
方法并进行一些手动检查。这样的事情可能会让你开始。
class MyForm(Form):
name = StringField('Name',
validators=[DataRequired(), Length(max=255)])
email = StringField('Email',
validators=[Optional(), Email(), Length(max=255)])
phone = StringField('Phone number',
validators=[Optional(), NumberRange(min=8, max=14)])
comment = TextAreaField(u'Comment',
validators=[DataRequired()])
def validate(self):
valid = True
if not Form.validate(self):
valid = False
if not self.email and not self.phone:
self.email.errors.append("Email or phone required")
valid = False
else:
return valid
答案 1 :(得分:2)
谢谢@reptilicus。我对它的工作进行了微小的修改。
self.email.data and self.phone.data
validate()
方法结束时返回有效而不是else
条件。def validate(self): valid = True if not Form.validate(self): valid = False if not self.email and not self.phone: self.email.errors.append("Email or phone required") valid = False return valid