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