Skip to content Skip to sidebar Skip to footer

Raising An Error In WTForm Using Jinja2

I'm trying to raise an error in Jinja2, in a WTForm, the error should be raised if url input is not validated, but when i submit an invalide url, i get a popup saying 'Please enter

Solution 1:

Because you're using the data type URLField, this is rendered as a HTML5 "url" form field type.

enter image description here

Your browser recognises this and performs its own validation on the data submitted:

enter image description here

There is no way for you to override this - it's built in to the browser.

If you need to show a custom error message, you might be able to use a TextField instead, and provide your own URL validation logic.


Solution 2:

Add your own message instead of default message in your form defination.

url = URLField('url', validators=[DataRequired(),url(message="Please enter a valid url (e.g.-http://example.com/)")]) 

Solution 3:

As Matt Healy before mentiones, it is the browser that validates URLField. So if you want a custom error message use StringField (TextField is outdated). If required, a custom message can be used as shown below message='text to display'. Example:

class XYZForm(FlaskForm):
    url = StringField('url', validators=[DataRequired(),url(message='Please enter valid URL')])
    description = StringField('description')

Of course the *.html should include code to output an error to the page:

                <ul>
                    {% for error in form.url.errors %}
                        <li>{{ error }}</li>
                    {% endfor %}
                </ul>

Solution 4:

It seems like novalidate attribute works for your case.


Post a Comment for "Raising An Error In WTForm Using Jinja2"