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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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")])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.