WTForm “OR” conditional validator? (Either email o

2019-07-08 05:13发布

问题:

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