How to Apply Form Validation in Node

Introduction 

 
This blog will explain form validation and what an express-validator is. It also goes over how to set up a node project and how we can apply server-side validation using an express-validator in our node application. 
 

What Is Form Validation?

 

Form validation is required to prevent web form abuse from malicious users. Improper validation of form data is one of the main causes of security vulnerabilities. It exposes your website to attacks such as header injections, cross-site scripting, and SQL injections.

  • Header injection attacks can be used to send email spam from your web server.
  • Cross-site scripting may allow an attacker to post any data to your site.
  • SQL injection may corrupt your database backend.

There are two different types of form validation that you'll encounter on the web: 

  • Client-side validation

Client-side validation occurs in the browser before the data has been submitted to the server. It is more user-friendly than server-side validation because it gives an instant response. Client-side validation is further subdivided into the following categories:

  • JavaScript validation is coded using JavaScript. This validation is completely customizable.
  • Built-in form validation uses HTML5 form validation features. This validation generally doesn't require JavaScript. Built-in form validation has better performance than JavaScript. While highly customizable, native validation is not as customizable as JavaScript.
  • Server-side validation

Validation occurs on the server after the data has been submitted. Server-side code is used to validate the data before the data is saved in the database or otherwise used by the application. If the data fails validation, a response is sent back to the client with corrections that the user needs to make. Server-side validation is your application's last line of defense against incorrect or malicious data. All popular server-side frameworks have features for validating and sanitizing data or making it safe.

What Is Express Validator?

Express Validator is a set of Express.js Middleware that wraps validator.js\, a library that provides validator and sanitizer functions. Simply put, Express Validator is an Express middleware library you can incorporate into your apps for server-side data validation.

Project Structure 
 
|-------------- views
                        |------------- register.ejs.
 
|-------------- app.js
 
|-------------- package.json 
 
 
How to Setup The Node Project
  • Create a new folder using console/terminal.
  • Open console/terminal, type mkdir followed by the folder name that you want to give.
  • Change to that folder by typing cd 'folder name'.


  • Now type npm init on your console/terminal.


  • The npm init will create a package.json file.
  • We can create it manually as well. Just open the folder, add a new file, and name it package.json.
  • It can be structured the same way as structured when using npm init.

    The package.json will look like this:


  • Now type npm install and install following packages express,ejs,body-parser,express-validator

     
  • This generates a folder name,node_modules, which will contain all the node packages.
  • Now add a new file and name it app.js.
  • Go back to package.json file, and in scripts, write "start": "node app.js". This will be the application entry point
  • Now the package.json will look like this:


  • Now add a folder name views.
  • In it, make a new file named register.ejs.


app.js
  1. var express                = require('express');  
  2. var bodyParser             = require('body-parser');  
  3. var path                   = require('path')  
  4. var {check,validationResult} = require('express-validator');  
  5.   
  6. var app = express();  
  7.   
  8. app.set("views",path.resolve(__dirname,'views'))  
  9. app.set('view engine','ejs');  
  10.   
  11. app.use(bodyParser.urlencoded({extended:false}))  
  12.   
  13. app.get('/',function(req,res){  
  14.     res.render('register',{data:{}})  
  15. })  
  16.   
  17. app.post('/',check('name').isLength(5).withMessage("enter name").isAlpha().withMessage("name should only have alpabets"),  
  18. check('email').isEmail().withMessage("enter vaild email"),  
  19. check('phno').isMobilePhone().withMessage("number is not correct")  
  20. ,function(req,res){  
  21.    var err = validationResult(req);  
  22.    if(!err.isEmpty()){  
  23.        console.log(err.array())  
  24.        res.render('register',{data:err.array()})  
  25.    }  
  26.    else{  
  27.    res.redirect('/')  
  28.    }  
  29. })  
  30.   
  31. var port = process.env.PORT || 3000;  
  32.   
  33. app.listen(port,function(){console.log('server running at port'+port)})  
  34.   
  35. module.exports=app;   
  • Applying server-side validation on app.post('/') route using express-validator.
  1. var {check,validationResult} = require('express-validator');
  2. app.post('/',check('name').isLength(5).withMessage("enter name").isAlpha().withMessage("name should only have alpabets"),
  3. check('email').isEmail().withMessage("enter vaild email"),
  4. check('phno').isMobilePhone().withMessage("number is not correct") ,function(req,res){
  5. var err = validationResult(req);
  6. if(!err.isEmpty()){
  7. console.log(err.array())
  8. res.render('register',{data:err.array()})
  9. }
  10. else{ res.redirect('/')
  11. }
  12. })
  • check() - the function specifies which data field you want to validate.here we validating name,email,phno data field.
  • withMessage() - specifies a custom error message which will be send back to your users if this particular field violates a validation requirement.
  • Validation happens in the request handler when it calls the validationResult() function.
  • Here we import the installed package express,body-parser,express-validator.Path from the build package.
    • express - is a framwork on which application will be built.
    • body-parser - will get Form Data out from the request.
    • app.set('views',path.resolve(__dirname,'views')) - tells express where the views folder is.
    • app.set('view engine','ejs') - this tells express that any file ending in .ejs should be rendered with ejs packages.
Views
  • register.ejs   
  1. <html lang="en">  
  2.  <head>  
  3.      <meta charset="UTF-8">  
  4.      <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  5.      <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  6.      <title>Document</title>  
  7.  </head>  
  8.  <body>  
  9.      <% if(data.length > 0) {%>  
  10.        <% for(var i=0; i< data.length; i++) {%>  
  11.         <div><%= data[i].msg%></div>  
  12.              <% } %>  
  13.         <% } %>  
  14.       <form action="/" method="POST">  
  15.      <input type="text" name="name" placeholder="enter the name"><br>  
  16.      <input type="text" name="email" placeholder="enter email"><br>    
  17.      <input type="text" name="phno" placeholder="enter phno"><br>    
  18.      <input type="submit" value="register"><br>    
  19.     </form>  
  20.  </body>  
  21.  </html> 

Summary

In this blog post, we learned about how to apply form-validation in node.