Form validation in NodeJS

nodejs-logo

Our Goals –
• Create a HTML Form and before submit validate the data with EJS Template

Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.

To do so –
1. Install express-validator by typing “npm install express-validator –save”
2. Open “home.ejs” from “app_views” folder and edit the file as –

<% include header %>
<body>
	<h1><%= topicHead %></h1>
	<form name="form1" method="POST" action="/student/add">
	<table>
		<tr>
		<td>First name</td>
		<td><input type="text" name="fname" ></td>
		</tr>
		<tr>
		<td>last name</td>
		<td><input type="text" name="lname" ></td>
		</tr>
		<tr>
		<td colspan="2"><input type="submit" value="Save" ></td>
		</tr>
	</table>
	</form>
	<% if(errors){ %>	
		<ul>
		<% errors.forEach(function( err){ %>
			<li> <%= err.msg %> </li>
		<% }) %>
		</ul>
	<%}else{%>
		<div> Data Entered as <%= userValue.first %>  <%= userValue.last %> </div>
	<%}%>	
</body>
<% include footer %>

<% include footer %>
3. Edit “app.js” as –

var express = require('express');
var parser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var app = express();
app.set('port',(process.env.PORT || 5000));
app.use(parser.urlencoded({ extended: false }))
app.use(parser.json())

app.use(function(req,res,next){
	res.locals.userValue = null;
	res.locals.errors = null;
	next();
})

app.set('view engine','ejs');
app.set('views',path.join(__dirname,'app_views'))

// From - https://github.com/ctavan/express-validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
// End of express-validator

app.get('/',function(req,res){
	res.render('home',{
		topicHead : 'Student Form'
	});
	console.log('user accessing Home page');
});
app.post('/student/add',function(req,res){
	
	// Check Input Field
	req.check('fname', 'First Name is required').notEmpty();
	req.check('lname', 'Last Name is required').notEmpty();
	
	var errors = req.validationErrors();
	if(errors){
		res.render('home',{
			topicHead : 'Student Form',
			errors : errors
		});
		console.log('Error');
	}else{
		var student = {
			first : req.body.fname,
			last : req.body.lname
		}
		console.log(student);
		res.render('home',{
			userValue : student,
			topicHead : 'Student Form'
		});
		console.log('OK');
	}	
});
app.listen(app.get('port'),function(){
	console.log('server running on port '+app.get('port'));
})

4. Considering we have installed “nodemon” in our nodejs and run “nodemon”

5. Now browser will show our first EJS template based web Form @ http://localhost:5000/

6. Without entering any value hit the submit button and you will get the following screen-

7. Now provide First name as “tanmay and Last name as “sarkar” and click Save button , it will looks like –

Thank you.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *