Form Validation in Node.js with Express-Validator

Screen Shot 2013-04-06 at 7.19.54 PM
I spent a good amount of time scouring the internet for a good form validation tutorial using Node.js. Since I was only able to find one decent tutorial I decide to write my own using express-validator, which is an express.js middleware for node-validator. If your using Node.js and your not using Express then you aren’t in the “in” crowd. Express is easily the most popular module available for Node.

We’ll start off by creating our project and installing express.

mkdir FormValidation
cd FormValidation
express -c stylus
npm install -d

Next we’ll install express-validator.

npm install express-validator

Installing express should of automatically created your app.js file along with routes, views, etc. Open up app.js and add the following code:

 * Module dependencies.

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , expressValidator = require('express-validator'); //Declare Express-Validator

var app = express();

  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(expressValidator);  //required for Express-Validator
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));

app.configure('development', function(){

app.get('/', function(req,res){
    res.render('index', { 
        title: 'Form Validation Example',
        message: '',
        errors: {}        

//Post'/', function(req,res){
    req.assert('name', 'Name is required').notEmpty();           //Validate name
    req.assert('email', 'A valid email is required').isEmail();  //Validate email

    var errors = req.validationErrors();  
    if( !errors){   //No errors were found.  Passed Validation!
        res.render('index', { 
            title: 'Form Validation Example',
        	message: 'Passed Validation!',
        	errors: {}
    else {   //Display errors to user
        res.render('index', { 
            title: 'Form Validation Example',
            message: '',
            errors: errors
http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));

I’ve added comments to the validation code required. We declare our express-validator with the following line:

expressValidator = require('express-validator'); //Declare Express-Validator

We also need to tell express to use the validator.

app.use(expressValidator);  //required for Express-Validator

We’ve added two routes, a get and a post. The post is where we do our validation with the following lines:

req.assert('name', 'Name is required').notEmpty();           //Validate name
req.assert('email', 'A valid email is required').isEmail();  //Validate email

A full list of validation methods can be found at node-validator. The next line fills an array object if errors exist:

var errors = req.validationErrors();

The errors are returned in the following format:

  {param: "name", msg: "Name is required", value: "<received input>"},
  {param: "email", msg: "A valid email is required", value: "<received input>"}

If errors exist we want to pass them back to our index view to display to the user.

extends layout

block content
  - function isEmptyObject(obj) {
  -      var name;
  -      for (name in obj) {
  -        return false;
  -      }
  -      return true;
  -    }
  h1= title
  - if (isEmptyObject(errors) == false)
    p.errorMessage= "The following errors occurred:"
      - each error in errors
        li= error.msg
  form( method="post")
        span.label Name :
        input(type="text", name="name", id="name")
        span.label Email :
        input(type="text", name="email", id="email")
        input(type="submit", value="Submit")
  p #{message}  

For demo purposes, we’ve added an isEmptyObject function to check whether our errors array is empty. If errors exist, we loop through each one and display the error message to the user. Thats all there is to validating your form with express and node.js. I’ve posted the source code on github. Feel free to improve on it any way you can.

Source code:


In order to put an error next to the corresponding field, it might be a good idea to map the errors to the field names by using req.validationErrors(true);

Can you be more specific in how I would use the req.validationErrors(true); if I have error checking on three different fields? Can you provide an example?

In this example, when there are errors, the page is re-rendered …i.e. res.render(…).. and the errors are passed to the page. However then all the form data that was entered by the user is lost. Is there a way to use express-validator on the client-side?

Thanks for the tutorial, hard to find decent docs (containing examples) regarding form validation in node. Cleared things up a lot.

If there is a server side error and you want to user to recover from that then a way to keep the form fields would be useful. The server side error could be momentry and you’d like to help the user out with keep the fields.

Thank you for the tutorial. I feel like a proper asshole to tell you this but I have seen so many people make this mistake I kinda have to tell you. Where you say “Installing express should of automatically” it is not “should of” it is “should have”. Common mistake though.

Leave a Reply

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

Please Do the Math      

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: