Want Validate Your Form data? Make It Automatic With WTForms

From Software Development point of view, Form Validation is a task that involved applying some rules that the data, inserted via the form, are expected to conform with. This is very important step as it helps the developer in making sure that only the accepted type of data, which is also in the acceptable format, are allowed to pass unto the next step for further processing.

Form can be validated from the client-side or from the server-side. In this tutorial, I will be using wtforms, a python library, and a flask, a simple and light weight web app framework, to generate, display and also validate the form from the server-side.

By default, python installation comes with a flask framework. But in case if yours didn’t, run the command below to install it:

$ pip install flask

Run the command below to install the wtforms library:

$ pip install wtforms

After successfully installing the two modules above, we are now ready to dive into the wonderful world of form auto generation and auto validation!

To generate a form, using wtforms, one needs to follow these simple steps:

  1. Import the required fields and the Form module
  2. Create the Form model
  3. Display the form (in the hmtl) and/or validate the data submitted via the form

Importing the Form class & the Fields

Form is the class we need to inherit in our models:  from wtforms import Form

All the fields/controls that we need to use in our form are already defined in the wtforms library. All we need to do is to import them and then put them into use (in our model). We also need to import validators, which is also a wtforms module  used in applying validation rules to our form.

For instance, if we want to use text fields , password field and checkbox, the general import, including the Form class, will look like:

from wtforms import Form, StringField, PasswordField, BooleanField, validators

Note: StringField is for text field, PasswordField is for text field with hidden password characters, BooleanField is for checkbox. To know more about the other available fields, click here

Creating the Form model

The form model is a class, which we need to create, which contains the definition of the form we want to use. This class also has to extend the Form module that we imported. A simple model for a login form, that uses the fields we imported above, can look like the following:

  class LoginForm(Form):
      username = StringField('Username',[validators.required(), validators.Length(min=3)])
      password = PasswordField('Password',[validators.required(),validators.Length(min=3)])
      remember_me = BooleanField('Remember Me') 

In the above form model, called LoginForm, we defined three fields (username, password and remember_me) which are the names we will be using to access the form controls in the html and in our server-side code. Each of the fields above is initialized with its label (such as Remember Me for the remember_me  field and the validation rules).

Displaying the form

Before we can display our form in the html, we need to create the object of the form model and then pass it in the function that render our template. Below is the route that displays our login page (or grabs data from our form based on type of request):

 #the '/' below indicates that this is default/index page
 @app.route('/',methods=['GET','POST'])
 def home_page():
      #create object of our LoginForm
      login_form = LoginForm()
      
      #check if our request is of GET type, then display form
      if request.method == 'GET':
            return render_template('home.html',login_form=login_form)
            
      else:
      #our request is of POST type which mean data is being submitted via the form
      
      #validate the login grab our data here and do something with it
      if login_form.validate() #check if the data conform to the rules
            username = login_form.username.data
            userpass = login_form.password.data
            stay_logged = login_form.remember_me.data #boolean yes or no
            
            #now that we have the data we can do what we like with it
      else: #if validation failed
      #some form's rules are violated, you can acess the errors in the template through login_form.errors 

 In our html, we need to display the form by accessing the form object that is passed through the render_template function. Below is how the html will look like:

     <form class="form">    
   {{login_form.username(class="form-control mb-3 mt-5",placeholder="Username",style="width:250px")}} 

    {{login_form.password(class="form-control mb-3",placeholder="Password", style="width:250px")}}   

   {{login_form.remember_me(class="form-control")}}<p >Remember me</p>     <button type="submit" class="btn btn-primary">Login</button>     </form>

 (if you don’t know about generating html using template, like jinja2, click here for short intro)

As you can see above, you can apply css classes and other attributes to the form elements.

This is my little intro to using wtform for generating and validating form inputs. If you are curious about how you can apply form generation and validation in your project, feel free to clone/download this my github repo which is a small blog website in which I made use of wtform in generating and validating my form elements and data (especially the login, signup, new and edit blog forms). If you have any difficulty understanding some parts of this tutorial feel  free to comment and/or connect with me as I’m always ready to help and be helped.  

Cheers!

Twitter: @AminuBishr

Leave a Reply

Your email address will not be published. Required fields are marked *