WTForm" OR"条件验证器? (电子邮件或电话)

时间:2016-07-20 16:58:31

标签: python flask wtforms flask-wtforms

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

2 个答案:

答案 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。我对它的工作进行了微小的修改。

  1. 必须检查数据字段self.email.data and self.phone.data
  2. 还必须在validate()方法结束时返回有效而不是else条件。
  3. 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