WTForms: Disable client-side validation on cancel WTForms: Disable client-side validation on cancel flask flask

WTForms: Disable client-side validation on cancel


Since you use Flask-Bootstrap's quick_form() macro, you can just set novalidate parameter to True to disable client-side validation (it will set a novalidate attribute to your HTML <form> element):

{{ wtf.quick_form(form, novalidate=True) }}

If you are using Bootstrap-Flask, the method is similar:

{{ render_form(form, novalidate=True) }}


The Required validator as well as the DataRequired and InputRequired which replace Required since version 3 of WTForms set the replace flag of the field. This flag is used to add the required attribute to the HTML representation of the field. My workaround is to manually create a validate function.

from wtforms.validators import ValidationErrordef _required(form, field):    if not field.raw_data or not field.raw_data[0]:        raise ValidationError('Field is required')class SequenceForm(FlaskForm):    name = StringField('Name:', validators=[_required, Length(1, 128)])    # some other fields here    submit = SubmitField('submit')    cancel = SubmitField('cancel')

This way there is no validation on the client-side and it is ensured that the view function is called on every submit or cancel.

Note

An even simpler solution is to subclass the InputRequired validator and overwrite the field_flags dictionary.

from wtforms.validators import InputRequiredclass MyInputRequired(InputRequired):    field_flags = ()class SequenceForm(FlaskForm):    name = StringField('Name:', validators=[MyInputRequired(), Length(1, 128)])


You could forbid rendering of the required attr.

class MyTextInput(wtforms.widgets.TextInput):    def __call__(self, field, **kwargs):        kwargs['required'] = False        return super().__call__(field, **kwargs)

For Python2 add args like this:super(MyTextInput, self)

and then:

name = StringField('Name:', validators=[Required(), Length(1, 128)], widget=MyTextInput())