How to override the html default "Please fill out this field" when validation fails in Flask?
Asked Answered
W

2

12

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')
Woosley answered 10/6, 2018 at 20:47 Comment(0)
E
14

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.

Egest answered 10/6, 2018 at 20:52 Comment(0)
G
0

in my code work this:

On html file:

{{ CustomForm(form.birth, class="form-control", required=False ) }}

On .py file:

birth = DateField('date of birth', validators=[DataRequired(message="My custom message")])
Guinness answered 8/9, 2021 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.