Creating Forms with Express Validator

The idea of the post over here is to explain the function of express-validator. This is one useful middleware to assist in validating and sanitizing forms in the post request. We will explain this in 3 parts:-

  1. Building forms
  2. Configuring the route
  3. Configuring the controller

Building the Form

<div class=”container pt-3″>

    <h1>Registration </h1>
</div>
 <% if (typeof alert != ‘undefined’){  %>
    <div class=”alert alert-warning alert-dismissible fade show” role=”alert”>
        <strong>Holy guacamole!</strong> You should check in on some of those fields below.
        <% alert.forEach((data)=>{ %>
            <%= data.msg %>
            <br>
        <% })%>
        <button type=”button” class=”btn-close” data-bs-dismiss=”alert” aria-label=”Close”></button>
      </div>
 <% }%>
<div class=”container”>
    <form action=”/register” method=”POST”>
        <div class=”form-group”>
            <label for=”name”>Name</label>
            <input type=”text” class=”form-control” id=”name” name=”name”>
        </div>
        <br>
        <div class=”form-group”>
            <label for=”username”>Username (Note: must be your email)</label>
            <input type=”text” class=”form-control” id=”username” name=”username”>
        </div>
        <br>
        <div class=”form-group”>
            <label for=”password”>Password</label>
            <input type=”text” class=”form-control” id=”password” name=”password”>
        </div>
        <div class=”form-group”>
            <label for=”phonenumber”>Phone Number</label>
            <input type=”text” class=”form-control” id=”phonenumber” name=”phonenumber”>
        </div>
        <div class=”form-group”>
            <label for=”address”>Address</label>
            <input type=”text” class=”form-control” id=”address” name=”address”>
        </div>
<!–School Info –>
         <br>
        <div class=”container p-3 text-white” style=’background-color:lightseagreen;’>
            <label for=”highestqualification”>What is your current highest qualification</label>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification1″ value=”SPM” checked>
            <label class=”form-check-label” for=”highestqualification1″>
            SPM – Sijil Pelajaran Malaysia
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification2″ value=”OLEVEL-IGCSE”>
            <label class=”form-check-label” for=”highestqualification2″>
            OLEVEL OR IGCSE Cambridge Exam
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification3″ value=”ALEVELS”>
            <label class=”form-check-label” for=”highestqualification3″>
           A LEVELS Cambridge Exam
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification4″ value=”UEC”>
            <label class=”form-check-label” for=”highestqualification4″>
           UEC Unfied Exam Certificate
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification5″ value=”FOUNDATION”>
            <label class=”form-check-label” for=”highestqualification5″>
           FOUNDATION
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification6″ value=”STPM”>
            <label class=”form-check-label” for=”highestqualification6″>
          STPM Sijil Tinggi Persekolahan Malaysia
            </label>
        </div>
        <div class=”form-check”>
            <input class=”form-check-input” type=”radio” name=”highestqualification” id=”highestqualification7″ value=”MASTER-PHD”>
            <label class=”form-check-label” for=”highestqualification7″>
           MASTER PHD
            </label>
        </div>
        </div>
        <div class=”container pt-3″>
        <label for=”eduinfo”>Write your academic results</label>
        <textarea name=”eduinfo” class=”form-control” id=”eduinfo” cols=”100″ rows=”10″>eg. Math A , Science A, BM and etc (Please provide minimnun subjects )”</textarea>
        </div>
        <br>
        <input class=’btn btn-success’ type=”submit”name=’submit’ value=”submit”>
        <br>
        <small>Make sure all information is correct</small>
    </form>
</div>
<br>

 

Building the Route

Chaining all the validation. There is a list of checking over here from validating and sanitizing.

const main = require(‘./controller/main’);
const express = require(‘express’);
const router = express.Router();
const { body, validationResult } = require(‘express-validator’);
router.get(‘/register’, main.register);
router.post(‘/register’,[
    body(‘name’,’Please enter your name’).notEmpty().isString().escape(),
    body(‘username’,’Please enter a proper email address’).notEmpty().isEmail().normalizeEmail().escape(),
    body(‘password’, ‘Password must be more than 6 characters’).notEmpty().isLength({min:6}).escape(),
    body(‘phonenumber’,’Enter your phone number’).notEmpty().isString().escape(),
    body(‘address’,’Please enter your address’).notEmpty().isString().escape(),
    body(‘highestqualification’,’Please select from the list’).notEmpty().isString().escape(),
    body(‘eduinfo’,’Please write your academic result. Do not use any special characters’).notEmpty().isString().escape(),
], main.registerform);

Building Controller

const { body, validationResult } = require(‘express-validator’);
exports.registerform= (req,res)=>{
    // validating the form info
    const errors = validationResult(req);
    if (!errors.isEmpty()) {  // if there are errors
     const alert = errors.array();
    return res.render(‘./pages/register’,{alert:alert });
      }
        const info = {
            name: req.body.name,
            username: req.body.username,
            phone: req.body.phonenumber,
            address: req.body.address,
            highestqualification: req.body.highestqualification,
            eduinfo: req.body.eduinfo
        };
console.log(info);
};