WTForm “OR” conditional validator? (Either email o

2019-07-08 05:37发布

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?

2条回答
唯我独甜
2楼-- · 2019-07-08 05:58

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
查看更多
神经病院院长
3楼-- · 2019-07-08 05:59

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
查看更多
登录 后发表回答