How To Apply Form Validation In Node.

Image by Gerd Altmann from Pixabay



  • Open the console and create a new folder named validations by typing command mkdir followed by folder name.
  • Change to the new folder by typing command cd validations. 

  • Now setup node project by typing npm init.This will auto generate a package.json file in folder.


  • now add a add.js file and then open the package.json and in "scripts" write "start":"app.js".
  • The package.json will look like this. 

  • Now type npm install followed by package name. We install the following packages: express ejs body-parser express-validator.

  • Now add a folder name views. And in it make a new file names 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;


  • we import the installed package express,body-parser,express-validator.Path is inbuild package.
  • express - is a framework on which application will be built.
  • body-parser - will get Form Data out from the request.
  • express-validator - will contain validation function.Here we using check,validationResult() function from this package.
  • check() - will check the field validation when request will come.
  • validationResult() - will take request as parameter and will return validation errors.which are been pointed out by the check() function.
  • 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.
  • app.post('/') - check() function will check three form fields name,email,phno.
  • name field we provide validation isLength(5) so length should be at least 5 characters and second is the it should contain only alphabets.
  • email we provide isEmail() which will check whether email format is correct or not.
  • phno we provide isMobilePhone()  which will check mobile number.
  • Here we will return error if validationResult() function contain errors.
  • We return err in array format .err.array() and on register page we will apply for loop to get the error.messages out.
      Views

        register.ejs
  
  
<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>

Comments

Popular posts from this blog

Upload And Download File In Node

How To Use Sequelize-Cli In Node

Setup Flask Project