【问题标题】:Flask-WTF OR validationFlask-WTF OR 验证
【发布时间】:2018-02-03 19:43:28
【问题描述】:

我正在尝试使用 0.14 Flask-wtf 制作电子邮件联系表格。
我想在我的发件人中包含一个“任何一个”验证,用户在提交时必须至少输入电子邮件或电话号码。
这个帖子在这里: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')

【问题讨论】:

    标签: python validation flask flask-wtforms


    【解决方案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)
    

    【讨论】:

    • 嗨。我厌倦了你的方法,似乎没有用。当我在任何字段中不提交任何内容时,表单会自行验证并显示名称/消息错误。但是当我填写姓名和信息时,将电子邮件/电话留空,表格已发布。
    • @GreenKoala 看起来问题是我没有使用 .data 引用实际值 - 试试吧。
    • 在 if 语句中,我仍然有上一个示例中的 self.phone.data。现在应该适应了。
    • 太棒了!感谢您的解决方案。您介意再解释一下如何使用 .data 吗?
    • 是的,没问题。所以每个表单域都是一个对象,它有属性错误、数据,可能还有一些我不知道的其他属性。所以如果你想真正看到它的价值,你必须做 form.emails.data 而不仅仅是 form.emails,这是我们之前做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2013-06-16
    相关资源
    最近更新 更多