In this blog we are going to discuss about the form field validation in NodeJS using express middleware.

Why to use middleware ?

There are several ways to validate the form fields in NodeJS but middleware is also on the best, simple and effective way to validate the form fields. And also the middleware can be utilized on any route so technically the same middleware can be used to validate multiple fields.

How to implement ?

Now for every request using this middleware, we are going to validate it based on four parameters, that includes:

  • check where the params exists or not
  • required or not
  • check param type
  • finally, run the validator function ( a custom function )

Let’s create a condition check within the middleware

Functions to validate fields

param is the object containing

  • param_name
    • Name of the parameter like email, password, username, first name, last name, etc
  • required
    • Indicates whether the is required or optional
  • type
    • Indicates the type of the field like integer, string, boolean, etc
  • validator_functions
    • Custom defined validator function returning true or false.

Now lets see each functions in the above diagram

functions used in middleware

And Now in Route Just use object to pass multiple params for validation

Route passing field details to middleware object

Your complete middleware codes look like

const validateParams = function (requestParams) {
    return function (req, res, next) {
        for (let param of requestParams) {
            if (checkParamPresent(Object.keys(req.body), param)) {
                let reqParam = req.body[param.param_name];
                if (!checkParamType(reqParam, param)) {
                    return res.status(400).send({
                        status: 400,
                        result: `${param.param_name} is of type ` +
                        `${typeof reqParam} but should be ${param.type}`
                    });
                } else {
                    if (!runValidators(reqParam, param)) {
                        return res.status(400).send({
                            status: 400,
                            result: `Validation failed for ${param.param_name}`
                        });
                    }
                }
            } else if (param.required){
                return res.status(400).send({
                    status: 400,
                    result: `Missing Parameter ${param.param_name}`
                });
            }
        }
        next();
    }
};

const checkParamPresent = function (reqParams, paramObj) {
    return (reqParams.includes(paramObj.param_name));
};

const checkParamType = function (reqParam, paramObj) {
    const reqParamType = typeof reqParam;
    console.log(` reqParamType : ${reqParamType} paramObj.type : ${paramObj.type}`);
    console.log(reqParamType === paramObj.type);
    return reqParamType === paramObj.type;
};

const runValidators = function (reqParam, paramObj) {
    for (let validator of paramObj.validator_functions) {
        console.log(`validator : ${validator}`);
        console.log(`reqParam : ${reqParam}`);
        if (!validator(reqParam)) {
            return false
        }
    }
    return true;
};

module.exports = {
    validateParams: validateParams
};

Source of the original middleware method: internet, it is implemented and modified by me.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.