我正在尝试使用 0.14 Flask-wtf 制作电子邮件联系表。
我想在我的发件人中包含一个“其中一个”验证,用户在提交时必须至少输入电子邮件或电话号码。
这篇文章在这里:WTForm "OR" conditional validator? (Either email or phone)正是我正在寻找的,但是,除了默认的 InputReuired 验证之外,它不起作用。有没有办法实现这种类型的验证?谢谢。
应用.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)
表格.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)
我是一名优秀的程序员,十分优秀!