Express-validator is a node's middleware that can be used as form validation or we can say to validate the body, params, query, headers and cookies of request object. It has its own validation rule, and if any of the applied validation rule is not satisfied, it will populate the response object with errors and return as a response.We can use this response in our view template to show the errors to users.
Lets say we have a registration form and we are going to use express-validator to validate the user input.
First we create an application using express generator with the commands below.
mkdir validation
cd validation
express formValidation
npm install
Next we will install express-validator.
npm install express-validator --save
Now open your app.js and add the following code:
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
app.use(express.bodyParser());
app.use(expressValidator()); // This line should be after express.bodyParser()!
Next we add two routes, a get and a post. Inside the post we do our validation with the following lines:
app.post('/, function(req, res) {
req.assert('name', 'Please enter name').notEmpty();
req.assert('email', 'Please enter a valid email').isEmail();
req.assert('password', 'Please enter password').notEmpty();
var errors = req.validationErrors();
if (errors) {
return res.render('index', {errors: errors});
} else {
return res.render('home', { errors: errors});
}
}
In the code above first we validate the form input, if there are any errors we will render the user to the same index page else we will render the user to the home page.Here i assume that you have index.jade, home.jade files in your view folder.
If errors exist we need to send the errors back to our index view to display to the user.
For that we need to add the following code in our index.jade file
extends layout
block content
h1= title
div
if errors
ul
for error in errors
li= error.msg
form(method='post', action='/')
label name:
input(type='text', name='name')
br
label email:
input(type='text', name='email')
br
br
label password:
input(type='password', name='password')
br
br
button(type='submit') Create
0 Comment(s)