Express middleware for the validator module.


An express.js middleware for node-validator.

This is basically a copy of a gist by node-validator author chriso.

npm install express-validator
var util = require('util'),
    express = require('express'),
    expressValidator = require('express-validator'),
    app = express.createServer();
app.use(expressValidator([options])); // this line must be immediately after express.bodyParser()!'/:urlparam', function(reqres) {
  // checkBody only checks req.body; none of the other req parameters 
  // Similarly checkParams only checks in req.params (URL params) and 
  // checkQuery only checks req.query (GET params). 
  req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
  req.checkQuery('getparam', 'Invalid getparam').isInt();
  // OR assert can be used to check on all 3 types of params. 
  // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); 
  // req.assert('urlparam', 'Invalid urlparam').isAlpha(); 
  // req.assert('getparam', 'Invalid getparam').isInt(); 
  var errors = req.validationErrors();
  if (errors) {
    res.send('There have been validation errors: ' + util.inspect(errors), 400);
    urlparam: req.param('urlparam'),
    getparam: req.param('getparam'),
    postparam: req.param('postparam')

Which will result in:

$ curl -d 'postparam=1' http://localhost:8888/test?getparam=1
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1
There have been validation errors: [
  { param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1ab
There have been validation errors: [
  { param: 'getparam', msg: 'Invalid getparam', value: '1ab' },
  { param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl http://localhost:8888/test?getparam=1&postparam=1
There have been validation errors: [
  { param: 'postparam', msg: 'Invalid postparam', value: undefined} ]

####errorFormatter function(param,msg,value)

The errorFormatter option can be used to specify a function that can be used to format the objects that populate the error array that is returned in req.validationErrors(). It should return an Object that has param, msg, and value keys defined.

// In this example, the formParam value is going to get morphed into form body format useful for printing. 
  errorFormatterfunction(parammsgvalue) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;
    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    return {
      param : formParam,
      msg   : msg,
      value : value

####customValidators { "validatorName": function(value, [additional arguments]), ... }

The customValidators option can be used to add additional validation methods as needed. This option should be an Object defining the validator names and associated validation functions.

Define your custom validators:

 customValidators: {
    isArrayfunction(value) {
        return Array.isArray(value);
    gtefunction(paramnum) {
        return param >= num;

Use them with their validator name:

req.checkBody('users', 'Users must be an array').isArray();
req.checkQuery('time', 'Time must be an integer great than or equal to 5').isInt().gte(5)

You have two choices on how to get the validation errors:

req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
req.assert('password', '6 to 20 characters required').len(6, 20);
var errors = req.validationErrors();
var mappedErrors = req.validationErrors(true);


  {param: "email", msg: "required", value: "<received input>"},
  {param: "email", msg: "valid email required", value: "<received input>"},
  {param: "password", msg: "6 to 20 characters required", value: "<received input>"}


  email: {
    param: "email",
    msg: "valid email required",
    value: "<received input>"
  password: {
    param: "password",
    msg: "6 to 20 characters required",
    value: "<received input>"

You can use the optional() method to check an input only when the input exists.

//if there is no error, is either undefined or a valid mail. 


<input name="user[fields][email]" />

Provide an array instead of a string:

req.assert(['user', 'fields', 'email'], 'valid email required').isEmail();
var errors = req.validationErrors();


    param: "user_fields_email",
    msg: "valid email required",
    value: "<received input>"

Alternatively you can use dot-notation to specify nested fields to be checked:

req.assert([''], 'valid email required').isEmail();

Express allows you to define regex routes like:

app.get(/\/test(\d+)/, function() {});

You can validate the extracted matches like this:

req.assert(0, 'Not a three-digit integer.').len(3, 3).isInt();

You can add your own validators using the customValidators option. See Middleware Options for usage details.

  • Update this readme
  • Added req.checkBody() (@zero21xxx).
  • Upgraded validator dependency to 1.1.3
  • req.validationErrors() now returns null instead of false if there are no errors.
  • Support for regex routes (@Cecchi)
  • Fix checkHeader() (@pimguilherme)
  • Add dot-notation for nested input (@sharonjl)
  • Add validate() alias for check()
  • Fix chaining validators (@rapee)
  • Added validationErrors() method (by @orfaust)
  • Added support for nested form fields (by @orfaust)
  • Added test cases
  • Readme update
  • Expose Filter and Validator instances to allow adding custom methods
  • Use req.param() method to get parameter values instead of accessing req.params directly.
  • Remove req.mixinParams() method.
  • Initial release
  • Christoph Tavan - Wrap the gist in an npm package
  • @orfaust - Add validationErrors() and nested field support
  • @zero21xxx - Added checkBody function

Copyright (c) 2010 Chris O'Hara, MIT License