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.configure(function(){
  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(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(expressValidator);  //required for Express-Validator
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

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

//Post
app.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.
index.jade

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:"
    ul  
      - each error in errors
        li= error.msg
  form( method="post")
    div
      div
        span.label Name :
        input(type="text", name="name", id="name")
      div
        span.label Email :
        input(type="text", name="email", id="email")
      div
        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: https://github.com/ijason/NodeJS-Form-Validation

10 Replies to “Form Validation in Node.js with Express-Validator”

  1. 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);

  2. 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?

  3. 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!

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

  5. 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.

  6. 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      
 

*