Tech Monger

Programming, Web Development and Computer Science.

Skip to main content| Skip to information by topic

Integrate Custom Validation in WTForms using Flask

While using WTF or Flask-WTF for the form validation you would often find yourself adding custom validation messages according to the requirement of your web application. You can always use WTF's ValidationError API however in this tutorial we will show you clever hack to add validation messages during page rendering. We will show example code with flask but you can use this method with any other framework which is using WTF for form validation.


Form Model

Lets assume that we have web app which asks users to submit Name and URL via form. We want to make URL field to accept only valid URL and field is mandatory. We can easily implement this functionality with the help of WTF's DataRequired and URL validators.

from flask_wtf import FlaskForm
from wtforms.fields import TextField
from wtforms.fields.html5 import  URLField
from wtforms.validators import DataRequired, URL


class URLForm(FlaskForm):
    name = TextField('Name', 
                    validators=[DataRequired(message="Enter Your Name Please")])

    url = URLField('URL', 
                    validators=[DataRequired(message="Enter URL Please"), 
                    URL(message="Enter Valid URL Please.")])

Custom Validation Checker

But in addition to that we only allow URLs submitted for the restricted sites (domains). For this we will need to write our own custom validation method and need to render validation error below URL field in our web form. In flask we will write custom validation check method.

def allowed_site(url):
    allowed_sites = ["example.com", "www.example.com"]

    # Will Fetch HOST Domain From URL
    # Example : https://example.com/abc/xyz >> example.com
    host = url.split('/')[2].lower()

    if host in allowed_sites:
        return True
    else:
        return False

Handling Post and Rendering Validation Error

We will return the submitted web form page upon the post request and render the validation errors if any using form.url.errors.

form.validate() method will automatically take care of validation error raised by WTF Form. However to check and render custom error we will need to append it inside the list form.url.errors during the runtime like below.

@app.route('/submiturl', methods=["GET", "POST"])
def submiturl():
    name = request.args.get('name', '')
    url = request.args.get('url', '')

    # form.validate() will validate WTF Validaors
    if request.method == 'POST' and form.validate():
        if not allowed_site(url):
            form.url.errors.append("This site is not allowed")

Conclusion

In above example we learned how we can append custom validation messages inside error list of the wtf's form field form.url.errors.append and implement custom validation.

Tagged Under : Flask Flask-WTF Open Source Python WTF Web