Code Monkey home page Code Monkey logo

express-validator's Introduction

express-validator

Build Status

An express.js middleware for node-validator.

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

Installation

npm install express-validator

Usage

var util = require('util'),
    express = require('express'),
    expressValidator = require('express-validator'),
    app = express.createServer();

app.use(express.bodyParser());
app.use(expressValidator([options]));

app.post('/:urlparam', function(req, res) {

  // checkBody only checks req.body; none of the other req parameters
  req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  req.assert('getparam', 'Invalid getparam').isInt();
  req.assert('urlparam', 'Invalid urlparam').isAlpha();

  req.sanitize('postparam').toBoolean();

  var errors = req.validationErrors();
  if (errors) {
    res.send('There have been validation errors: ' + util.inspect(errors), 500);
    return;
  }
  res.json({
    urlparam: req.param('urlparam'),
    getparam: req.param('getparam'),
    postparam: req.param('postparam')
  });
});

app.listen(8888);

Which will result in:

$ curl -d 'postparam=1' http://localhost:8888/test?getparam=1
{"urlparam":"test","getparam":"1","postparam":true}

$ 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} ]

Middleware Options

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

The errorFormatter option can be used to specify a function that can be used to formate the objects that populate the error arrow 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.
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
    };
  }
}));

Validation errors

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

errors:

[
  {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>"}
]

mappedErrors:

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

Nested input data

Example:

<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();
console.log(errors);

Output:

[
  {
    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(['user', 'fields', 'email'], 'valid email required').isEmail();

Regex routes

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();

Extending

You can extend the Validator and Filter objects to add custom validation and sanitization method.

Custom validation which always fails. Useful for debugging or for adding messages manually when doing complex validation:

var expressValidator = require('express-validator');

expressValidator.Validator.prototype.fail = function() {
  //You could validate against this.str, instead of just erroring out.

  this.error(this.msg);
  return this;
};

Custom sanitization which lower-cases the string:

expressValidator.Filter.prototype.toLowerCase = function(){
  this.modify(this.str.toLowerCase());
  return this.str;
};

Changelog

v0.4.1

  • Update this readme

v0.4.0

  • Added req.checkBody() (@zero21xxx).
  • Upgraded validator dependency to 1.1.3

v0.3.0

  • req.validationErrors() now returns null instead of false if there are no errors.

v0.2.4

  • Support for regex routes (@Cecchi)

v0.2.3

  • Fix checkHeader() (@pimguilherme)

v0.2.2

  • Add dot-notation for nested input (@sharonjl)
  • Add validate() alias for check()

v0.2.1

  • Fix chaining validators (@rapee)

v0.2.0

  • Added validationErrors() method (by @orfaust)
  • Added support for nested form fields (by @orfaust)
  • Added test cases

v0.1.3

  • Readme update

v0.1.2

  • Expose Filter and Validator instances to allow adding custom methods

v0.1.1

  • Use req.param() method to get parameter values instead of accessing req.params directly.
  • Remove req.mixinParams() method.

v0.1.0

  • Initial release

Contributors

  • Christoph Tavan [email protected] - Wrap the gist in an npm package
  • @orfaust - Add validationErrors() and nested field support
  • @zero21xxx - Added checkBody function

License

Copyright (c) 2010 Chris O'Hara [email protected], MIT License

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.