如何覆盖html默认的“请填写此字段"当Flask中的验证失败时? [英] How to override the html default "Please fill out this field" when validation fails in Flask?

查看:286
本文介绍了如何覆盖html默认的“请填写此字段"当Flask中的验证失败时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Flask-WTF表单,其中包含DataRequired验证器和相关的错误消息.但是,Chrome浏览器似乎忽略了我的错误消息,仅显示请填写此字段".如何让Flask覆盖它并显示我的消息?

I have a Flask-WTF form with with DataRequired validators and related error messages. However, the Chrome browser seems to ignore my error messages and just displays "Please fill out this field". How do I get Flask to override this and show my messages?

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired

class SignupForm(FlaskForm):
    first_name = StringField('First Name', validators=[DataRequired(message='Hey, put in your first name!')])
    last_name = StringField('Last Name', validators=[DataRequired("What, you can't remember your last name?")])
    email = StringField('Email', validators=[DataRequired('Gonna need your email address!')])
    password = PasswordField('Password', validators=[DataRequired('Really need a password, Dude!')])
    submit = SubmitField('Sign Up')

推荐答案

required 属性. Field.flags" rel ="nofollow noreferrer">必需";标记.这样,客户端可以执行一些基本的验证,从而节省了往返服务器的时间.

As of WTForms 2.2, the HTML required attribute is rendered when the field has a validator that sets the "required" flag. This allows the client to perform some basic validations, saving a round-trip to the server.

您应该将其留给浏览器来处理.这些消息是标准消息,并针对用户计算机的区域设置进行了调整.有一个JavaScript API可以控制这些消息(请参见堆栈溢出 MDN ),尽管WTForms不提供任何内容与它集成(不过,是扩展的一个好主意).

You should leave it to the browser to handle this. The messages are standard and adjusted for the user's computer's locale. There is a JavaScript API to control these messages (see Stack Overflow and MDN), although WTForms doesn't provide any integration with it (yet, a good idea for an extension).

如果您真的要禁用此功能,则可以在呈现字段时通过required=False.

If you really want to disable this, you can pass required=False while rendering a field.

{{ form.name(required=False) }}

您可以通过覆盖Meta.render_field来禁用整个表单.

You can disable it for a whole form instead by overriding Meta.render_field.

class NoRequiredForm(Form):
    class Meta:
        def render_field(self, field, render_kw):
            render_kw.setdefault('required', False)
            return super().render_field(field, render_kw)

您可以通过从禁用它的基本表单继承来对多种表单禁用它.

You can disable it for multiple forms by inheriting from a base form that disables it.

class UserForm(NoRequiredForm):
    ...

您还可以通过设置 HTML form标记上的rel ="nofollow noreferrer"> novalidate 属性.

You can also disable client validation without changing as much code by setting the novalidate attribute on the HTML form tag.

<form novalidate>

</form>

请参阅有关添加此行为的请求请求的讨论.

这篇关于如何覆盖html默认的“请填写此字段"当Flask中的验证失败时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆