Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to validate Form (Form Validation) in Node.Js?

Install Express Validator Module.

File Name :

c:\mynodeproject\nodeapp> npm install –save express-validator
######################### OR ##########################
npm install express-validator@5.3.0
// install specific version

npm uninstall express-validator

Create an HTML Form for Validation.

Create an HTML form with following input fields like :-

  • First Name
  • Last Name
  • Email
  • Password
  • Address
  • This HTML form will be used to validate the input data.

    File Name : user-form.ejs

    <!DOCTYPE html>
    <html>
    <head>
    <head>
    <body>

    <form action="/validate-form" method="POST">
    <label>First Name</label>
    <input type="text" placeholder="Enter First Name" name="firstName" value="<%=(typeof inputData!='undefined')? inputData.firstName:''%>">
    <p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.firstName!='undefined' )? errors.firstName.msg:''%></p>
    <label>Last Name</label>
    <input type="text" placeholder="Enter Last Name" name="lastName" value="<%=(typeof inputData!='undefined')? inputData.lastName:''%>">
    <p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.lastName!='undefined' )? errors.lastName.msg:''%></p>
    <label>Email Address</label>
    <input type="email" placeholder="Enter Email Address" name="emailAddress" value="<%=(typeof inputData!='undefined')? inputData.emailAddress:''%>">
    <p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.emailAddress!='undefined' )? errors.emailAddress.msg:''%></p>
    <label>Password</label>
    <input type="password" placeholder="Enter Password" name="password">
    <p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.password!='undefined' )? errors.password.msg:''%></p>
    <label>Confirm Password</label>
    <input type="confirmPassword" placeholder="Enter Confirm Password" name="confirmPassword">
    <p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.confirmPassword!='undefined' )? errors.confirmPassword.msg:''%></p>
    <button type="submit">Submit</button>
    </form>

    </body>
    </html>

    Write Rules for Form Validation

    Include express validator module using require('express-validator')

    Write all the validation rules within the exports.form=[]

    File Name : validation-rule.js

    const { check,sanitizeBody } = require('express-validator');
    exports.form=[
    // first Name validation
    check('firstName').trim().notEmpty().withMessage('First Name required')
    .matches(/^[a-zA-Z ]*$/).withMessage('Only Characters with white space are allowed'),
    // last Name validation
    check('lastName').notEmpty().withMessage('Last Name required')
    .matches(/^[a-zA-Z ]*$/).withMessage('Only Characters with white space are allowed'),
    // email address validation
    check('emailAddress').notEmpty().withMessage('Email Address required').normalizeEmail().isEmail().withMessage('must be a valid email'),
    // password validation
    check('password').trim().notEmpty().withMessage('Password required')
    .isLength({ min: 5 }).withMessage('password must be minimum 5 length')
    .matches(/(?=.*?[A-Z])/).withMessage('At least one Uppercase')
    .matches(/(?=.*?[a-z])/).withMessage('At least one Lowercase')
    .matches(/(?=.*?[0-9])/).withMessage('At least one Number')
    .matches(/(?=.*?[#?!@$%^&*-])/).withMessage('At least one special character')
    .not().matches(/^$|\s+/).withMessage('White space not allowed'),
    // confirm password validation
    check('confirmPassword').custom((value, { req }) => {
    if (value !== req.body.password) {
    throw new Error('Password Confirmation does not match password');
    }
    return true;
    })
    ]

    Validate Input data on the form Submit

  • Include the express validator and assign it to the validationResult & matchedData
  • Create a method userForm with the GET method to display the user form in the browser.
  • create another method validateForm with POST method to validate the input data. This method will be called when you submit the form.
  • File Name : user-controller.js

    const { validationResult, matchedData } = require('express-validator');
    module.exports={
    userForm:function(req, res) {
    res.render('user-form');
    },
    validateForm:function(req,res){
    const errors= validationResult(req);
    if(!errors.isEmpty()){
    var errMsg= errors.mapped();
    var inputData = matchedData(req);

    }else{
    var inputData = matchedData(req);
    // insert query will be written here
    }
    res.render('user-form', {errors:errMsg, inputData:inputData});
    }
    }

    Create Routes to Validate Form

    Create '/validate-form with the GET method to display the form
    create /validate-form with POST method to validate the form on the form submit’
    finally export the router.

    File Name : user-route.js

    const express = require('express');
    const router = express.Router();
    const userController=require('../controllers/user-controller');
    const validationRule= require('../middlewares/validation-rule');

    router.get('/validate-form', userController.userForm);
    router.post('/validate-form',validationRule.form, userController.validateForm);

    module.exports = router;

    Include the Route in the app.js

    File Name : app.js

    var userRouter = require('./routes/user-route');
    app.use('/', userRouter);

    Run Node.js Application

    File Name : app.js

    npm start

    Test on browser

    http://localhost:3000/validate-form

    Error :-

    app.use(expressValidator()); ^ TypeError: expressValidator is not a function at Object. (/home/kirankamath/A/Project/node_react/basicNodeServer/app.js:26:9) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

    solution :-

    While using version 6, you will encounter the following error:
    TypeError: expressValidator is not a function
    To avoid this issue you can use the previous version which is 5.3.1

    TypeError: expressValidator is not a function issue by reinstall the express validator NPM package and run the server again.

    npm uninstall express-validator
    npm install express-validator@5.3.0





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here