Node.js Form Validation – How to Validate the Form in Node.js Express

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 the time on this tutorial and share it with your friend too.

Node.js Form Validation

Node.js Form Validation Using Express-Validator

Before Writing validation Script, You  will have to do the following things

myapp/
  |__bin/
  |__config/
  |     |__form-validation.js
  |__controllers/
  |     |__validation-controller.js
  |__node_modules/
  |__public/
  |__routes/
  |     |__validation-route.js
  |__views/
  |     |__validation-form.ejs
  |__package-lock.json
  |__package.json

Install express-validator Module

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

npm install --save express-validator

Create HTML Validation Form

  • Create a file validation-form.ejs in the views folder
  • write the following HTML code to create validation form

File Path: views/validation-form.ejs

<form action="/form-validation" method="POST">
   <label>First Name</label>
   <input type="text" placeholder="Enter First Name" name="firstName">
           
   <label>Last Name</label>
   <input type="text" placeholder="Enter Last Name" name="lastName">
         
   <label>Email Address</label>
   <input type="email" placeholder="Enter Email Address" name="emailAddress">
         
   <label>Password</label>
   <input type="password" placeholder="Enter Password" name="password">
         
   <label>Confirm Password</label>
   <input type="confirmPassword" placeholder="Enter Confirm Password" name="confirmPassword">
         
   <button type="submit">Submit</button>
  • Each form field will be validated by using its own name. So, you must declare the name as the following table.
Form Field  Field Name
First Name firstName
Last Name lastName
Email Address emailAddress
Password password
Confirm Password confirmPassword
  • The form will be validated through the post method. So, you must declare it using the following attribute
method="POST"

 

Write Validation Script using express-validator

  • Create  a folder config
  • Create a file  form-validation.js
  • Write the following script in the form-validation.js file

File Name: form-validation.js

exports.register=[

// all the validation will be defined here
]
  • Load the following express-validator scripts in the form-validation.js
const { validationResult, matchedData } = require('express-validator');

First Name Validation

Write the following script to validate the first Name

// 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

Write the following script to validate the Last Name

// 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

Write the following script to validate the Email Address

// email address validation
  check('emailAddress').notEmpty().withMessage('Email Address required').normalizeEmail().isEmail().withMessage('must be a valid email'),

Password Validation

Write the following script to validate the Password

// 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

Write the following script to validate the confirm password

// confirm password validation
check('confirmPassword').custom((value, { req }) => {
     if (value !== req.body.password) {
           throw new Error('Password Confirmation does not match password');
      }
      return true;
 })

Complete Validation Script:

Use the following complete validation script in the form-validation.js

File Path: config/form-validation.js

const { check,sanitizeBody } = require('express-validator');
exports.register=[

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

 

Create Validation Controller

  • Create a file validation-controller.js in the controllers folder.

File Name: validation-controller.js

module.exports={

    // Here all the module will be defined
    },
  • Load the following express-validator scripts in the validation-controller.js
const { validationResult, matchedData } = require('express-validator');
  • Write the following script in the validation-controller.js to display the validation form in the web browser.
validationForm:function(req, res) {
    res.render('validation-form');
},
  • Write the following script in the validation-controller.js to post & validate the validation form.
postValidationForm:function(req,res){
        const errors= validationResult(req);
        if(!errors.isEmpty()){
          var invalidData= errors.mapped();
          var inputData = matchedData(req);  
    
         }else{
            var inputData = matchedData(req);  
           // insert query will be written here
        }
          res.render('validation-form', {errors:invalidData, inputData:inputData});
    }

Complete validation controller Script:

Use the following script in the validation-controller.js file

File Path: controllers/validation-controller.js

const { validationResult, matchedData } = require('express-validator');

module.exports={

    validationForm:function(req, res) {
        res.render('validation-form');
    },
    postValidationForm:function(req,res){
        const errors= validationResult(req);
        if(!errors.isEmpty()){
          var invalidData= errors.mapped();
          var inputData = matchedData(req);  
    
         }else{
            var inputData = matchedData(req);  
           // insert query will be written here
        }
          res.render('validation-form', {errors:invalidData, inputData:inputData});
    }
}

Display Validation Error Message

Use the following code to display the validation error message.

File Name: validation-form.ejs

<form action="/form-validation" 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>

Complete validation HTML form 

Use the following validation HTML form with customized in the  validation-form.ejs

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;}
.user-detail {
height: 100vh;
border: 2px solid #f1f1f1;
padding: 16px;
background-color: white;
width: 30%;}
input{
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;}
button[type=submit] {
background-color: #434140;
color: #ffffff;
padding: 10px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
font-size: 20px;}
label{
font-size: 18px;;}
button[type=submit]:hover {
background-color:#3d3c3c;}
</style>
</head>
<body>
<!--====form section start====-->
<div class="user-detail">
<h2>Node.js Form validation</h2>
<p>How to validate Form Using Node.js and MySQL</p>
<hr>
<form action="/form-validation" 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>
</div>
</div>
<!--====form section start====-->
</body>
</html>

 

Create Validation Route

Create validation-route.js file in the routes folder & load the following modules.

  • express & Router
const express = require('express'); 
const router = express.Router();
// all the routes will be defined here
module.exports = router;
  • validation-controller.js
const validationController=require('../controllers/validation-controller');
  • form-validation.js
const formValidation= require('../config/form-validation');

Now, Create the following route to  display validation form

router.get('/form-validation', validationController.validationForm);

Even Create the following route to submit & validate the form data

router.post('/form-validation',formValidation.register,validationController.postValidationForm);

Complete Validation Route:

Use the following complete  validation route in the validation-route.js

File Path: routes/validation-route.js

const express = require('express');
const router = express.Router();
const validationController=require('../controllers/validation-controller');
const formValidation= require('../config/form-validation');
router.get('/form-validation', validationController.validationForm);
router.post('/form-validation',formValidation.register,validationController.postValidationForm);
module.exports = router;

Load Validation Route

At last, You must load the following validation route in the main file app.js

var validationRouter = require('./routes/validation-route');
app.use('/', validationRouter);

 

 

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.

 

 

 

2 thoughts on “Node.js Form Validation – How to Validate the Form in Node.js Express”

  1. Hi, i have one query where can i load validation route in the main file app.,js.
    i am getting an error as .src/App.js line **:** “app” is not defined no-undef

    please help me to rectify this error

    Reply
    • Hi Sai, You need to check the following points

      • Right path of validation route file
      • validationRoute variable must be matched with passing it in app.use() method as a parameter

      Then you error will be definately solved

      Reply

Leave a Comment