WTForm “OR” conditional validator? (Either email or phone)

我是研究僧i 提交于 2019-12-12 20:25:59

问题


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

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


回答1:


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



回答2:


Thank you @reptilicus. I had minor changes to the answer for it to work.

  1. Had to check for data field self.email.data and self.phone.data
  2. Also had to return valid at the end of the validate() method instead of else condition.
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


来源:https://stackoverflow.com/questions/38486527/wtform-or-conditional-validator-either-email-or-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!