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 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.
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.
- 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
- var express = require('express');
- var bodyParser = require('body-parser');
- var path = require('path')
- var {check,validationResult} = require('express-validator');
-
- var app = express();
-
- app.set("views",path.resolve(__dirname,'views'))
- app.set('view engine','ejs');
-
- app.use(bodyParser.urlencoded({extended:false}))
-
- app.get('/',function(req,res){
- res.render('register',{data:{}})
- })
-
- app.post('/',check('name').isLength(5).withMessage("enter name").isAlpha().withMessage("name should only have alpabets"),
- check('email').isEmail().withMessage("enter vaild email"),
- check('phno').isMobilePhone().withMessage("number is not correct")
- ,function(req,res){
- var err = validationResult(req);
- if(!err.isEmpty()){
- console.log(err.array())
- res.render('register',{data:err.array()})
- }
- else{
- res.redirect('/')
- }
- })
-
- var port = process.env.PORT || 3000;
-
- app.listen(port,function(){console.log('server running at port'+port)})
-
- module.exports=app;
- Applying server-side validation on app.post('/') route using express-validator.
- var {check,validationResult} = require('express-validator');
- app.post('/',check('name').isLength(5).withMessage("enter name").isAlpha().withMessage("name should only have alpabets"),
- check('email').isEmail().withMessage("enter vaild email"),
- check('phno').isMobilePhone().withMessage("number is not correct") ,function(req,res){
- var err = validationResult(req);
- if(!err.isEmpty()){
- console.log(err.array())
- res.render('register',{data:err.array()})
- }
- else{ res.redirect('/')
- }
- })
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
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- </head>
- <body>
- <% if(data.length > 0) {%>
- <% for(var i=0; i< data.length; i++) {%>
- <div><%= data[i].msg%></div>
- <% } %>
- <% } %>
- <form action="/" method="POST">
- <input type="text" name="name" placeholder="enter the name"><br>
- <input type="text" name="email" placeholder="enter email"><br>
- <input type="text" name="phno" placeholder="enter phno"><br>
- <input type="submit" value="register"><br>
- </form>
- </body>
- </html>
Summary
In this blog post, we learned about how to apply form-validation in node.