Validation library for Node.js

ajsie picture ajsie · Nov 3, 2010 · Viewed 59.5k times · Source

Is there a good validation framework for node.js that validates a variable for:

  • if its a type of String, Date, Number etc
  • max and min length
  • email, phone
  • etc...

Answer

Baggz picture Baggz · Dec 23, 2010

I recently discovered node-validator by chriso.

Example

var check = require('validator').check,
    sanitize = require('validator').sanitize

//Validate
check('[email protected]').len(6, 64).isEmail();       //Methods are chainable
check('abc').isInt();                               //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt();      //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);

//Sanitize / Filter
var int = sanitize('0123').toInt();                  //123
var bool = sanitize('true').toBoolean();             //true
var str = sanitize(' \s\t\r hello \n').trim();      //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a');        //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('&lt;a&gt;').entityDecode();     //'<a>'