How to override the html default “Please fill out this field” when validation fails in Flask?

喜你入骨 提交于 2019-12-06 01:49:33

问题


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

回答1:


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.

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

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

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

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):
    ...

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

<form novalidate>

</form>

See the discussion on the pull request adding this behavior.



来源:https://stackoverflow.com/questions/50787904/how-to-override-the-html-default-please-fill-out-this-field-when-validation-fa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!