WTForm“或"表示有条件的验证者? (电子邮件或电话) [英] WTForm "OR" conditional validator? (Either email or phone)

查看:120
本文介绍了WTForm“或"表示有条件的验证者? (电子邮件或电话)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()])

是否始终要指定验证器,以便需要emailphone?

Is there anyway to specify a validator such that either email or phone is required?

推荐答案

您可以在表单上创建validate方法并进行一些手动检查.这样的事情可能会让您入门.

You can create a validate method on the form and do some manual checking. Something like this might get you started.

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

这篇关于WTForm“或"表示有条件的验证者? (电子邮件或电话)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆