我正在尝试使用0.14 Flask-wtf制作电子邮件联系表格。
我想在我的发件人中包含"任一"验证,用户在提交时必须至少输入电子邮件或电话号码。
这篇文章在这里 : WTForm "OR" 条件验证器?(电子邮件或电话(正是我正在寻找的,但是,除了默认的输入验证之外,它不起作用。有没有办法实现这种类型的验证?谢谢。
app.py
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate_on_submit() == False:
message = 'All fields are required.'
flash(message)
return render_template('contact.html', form=form)
else:
return 'Form posted.'
elif request.method == 'GET':
return render_template('contact.html', form=form)
Forms.py
class ContactForm(FlaskForm):
name = StringField('Name',
validators=[InputRequired(message='Please enter your name.')])
email = StringField('Your Email',
validators=[Optional(), Email(message='Please check the format of your email.')])
phone = StringField('Your Phone Number', validators=[Optional()])
word = TextAreaField('Your messages',
validators=[InputRequired(message='Please say something.')])
submit = SubmitField('Send')
不是在 Forms.py 内而是在 app.py 中执行此操作可能更容易。
例如
def is_valid(phone):
try:
int(phone)
return True if len(phone) > 10 else False
except ValueError:
return False
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate_on_submit() == False:
message = 'All fields are required.'
flash(message)
return render_template('contact.html', form=form)
else:
if not (form.email.data or form.phone.data):
form.email.errors.append("Email or phone required")
return render_template('contact.html', form=form)
else if not is_valid(form.phone.data):
form.phone.errors.append("Invalid Phone number")
return render_template('contact.html', form=form)
return 'Form posted.'
elif request.method == 'GET':
return render_template('contact.html', form=form)