Flask-WTF OR验证

时间:2018-02-03 19:43:28

标签: python validation flask flask-wtforms

我正在尝试使用0.14 Flask-wtf制作电子邮件联系表。
我想包括一个"其中一个"我的来自验证,哪个用户在提交时必须输入aleast电子邮件或电话号码。
这篇文章:WTForm "OR" conditional validator? (Either email or phone)正是我正在寻找的,但它与默认的InputReuired验证不同。 有没有办法实现这种类型的验证?感谢。

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')

1 个答案:

答案 0 :(得分:1)

这可能更容易,不是在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)
相关问题