• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to secondary sidebar

CodingStatus

- Level Up Your Status with Coding Expertise!

  • Tutorials
    • React Js Tutorials
    • JavaScript Tutorials
    • PHP Tutorials
    • HTML Tutorials
    • SQL Tutorials
    • Laravel Tutorials
  • Snippets
    • React Js Code Snippets
    • Ajax Code Snippets
    • Node.js Code Snippets
    • JavaScript Code Snippets
    • jQuery Code Snippets
    • SQL Code Snippets
  • Programs
    • PHP Program
    • Python Programs
    • Java Programs
  • How To
    • React Js How To
    • Node Js How To
    • Ajax How To
    • PHP How To
    • jQuery How To
    • JavaScript How to
  • Scripts
    • PHP Script
    • Js Script
    • React Js Script
    • JQuery Script
  • Projects
    • PHP Project
  • Interview Questions
  • Guide
  • API Integration
  • Installation

Node.js Form Validation with an Example

December 11, 2020 By Md Nurullah

Node.js Form Validation: Validation is the most important feature of the form. It is necessary to protect the form from illegal input. So, Node.js  provides the express-validator module to validate the user Input data. In this tutorial, you will know how to validate the form in node.js express.

I have shared the best example with the simple validation script using the express-validator module. Even I will suggest the best & simple way to validate the form. Therefore, give them time to this tutorial and share it with your friend too.

node.js form validation

Table of Contents

  • How to Validate Form Using Express-Validator in Node.js
    • 1. Install Express Application
    • 2. Install Express Validator Module
    • 3. Create an HTML Form to Validate
    • 4. Write Form Validation Rules
    • 5. Validate Input data on the form Submit
    • 6. Create Routes to Validate Form
    • 7. Include the Route in the app.js
    • 8. Run Node.js App to Validate the Form
    • My Suggestion

How to Validate Form Using Express-Validator in Node.js

Now, Configure all the following steps to validate the form.

1. Install Express Application

Install Basic Express Application and create the following required folders & files.

nodeapp/
  |__middlewares/
  |     |__validation-rule.js
  |__controllers/
  |     |__user-controller.js
  |__routes/
  |     |__user-route.js
  |__views/
  |     |__user-form.ejs
  |

2. Install Express Validator Module

First of all, Install express-validator using the following command with npm

nodeapp> npm install –save express-validator

3. Create an HTML Form to Validate

Create an HTML form with input fields like First Name, Last Name, Email Address, Password & Confirm Password. This form will be used to validate the input data. But This form must have the following two attributes –

  • action=”/validate-form”
  • method=”POST”

Path – 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>

 

4. Write Form Validation Rules

You should create a middleware to write validation rules.

  • First, Include express validator module using require('express-validator')
  • Write all the validation rules within the exports.form=[]

Path – 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;
   })
]

5. Validate Input data on the form Submit

Now, you have to create a controller to validate the form when you submit input data with the POST method. So, let’s create it through the following steps –

  • 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.
  • Also, create another method validateForm with POST method to validate the input data. This method will be called when you submit the form.

Path – 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});
    }
}

6. Create Routes to Validate Form

Now, Create the following two routes to validate the form

  • Create '/validate-form with the GET method to display the form
  • Also, create /validate-form with POST method to validate the form on the form submit’
  • At last. export the router.

Path – 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;

 

7. Include the Route in the app.js

At last, Don’t forget to load the following validation route in the main file app.js.

File Name – app.js

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

8. Run Node.js App to Validate the Form

First of All, start the node.js server and enter the following URL in your browser. after that submit the form with input data.  Your input values do not match the validation rule then It will display an error message otherwise it will allow you to submit the form.

http://localhost:3000/validate-form

Here I  have taken a simple form to validate their input data. After learning it, you can implement this code for validating any kind of form like registration, login, contact form & other.

My Suggestion

Dear developers, I hope you have understood the above script and you are able to validate the form in Node.js express. Now, you can easily validate another form in Node.js express

If you have any doubts or questions. You can directly ask me through the below comment box.

Filed Under: Node.js Code Snippets

Hello Developer, Welcome to my Blog. I'm Md Nurullah, a software engineer with 5+ years in full-stack web development. As the founder of CodingStatus.com, I'm passionate about sharing coding knowledge and collaborating for a brighter future. Let's connect and code together!

Primary Sidebar

Secondary Sidebar

Node.js Code Snippets,
  • Upload Multiple Files Using Multer in Node.js and Express
  • Node.js Send Email – Sending mail using Nodemailer
  • Fetch data from MongoDB Using Mongoose and Node.js Express
  • Node.js Form Validation with an Example
  • Node.js MySQL CRUD Operation with Example
  • Create Registration and Login Form in Node.js & MySQL
  • Node.js MySQL Connection Step By Step
  • MongoDB CRUD Operations Using Node.js Express and Mongoose
  • Connect MongoDB with Node.js Using Mongoose
  • Express MVC Structure – Model, View and Controller
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved