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