Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

express-validator

Package Overview
Dependencies
Maintainers
1
Versions
125
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-validator - npm Package Compare versions

Comparing version
0.1.3
to
0.2.0
+4
.travis.yml
language: node_js
node_js:
- 0.4
- 0.6
test:
for F in test/*.js; do echo "$$F: "; node $$F; done;
.PHONY: test
var assert = require('assert');
var async = require('async');
var App = require('./helpers/app');
var req = require('./helpers/req');
var port = process.env.NODE_HTTP_PORT || 8888;
var url = 'http://localhost:' + port;
// There are three ways to pass parameters to express:
// - as part of the URL
// - as GET parameter in the querystring
// - as POST parameter in the body
// URL params take precedence over GET params which take precedence over
// POST params.
var errorMessage = 'Parameter is not an integer';
var validation = function(req, res) {
req.assert('testparam', errorMessage).notEmpty().isInt();
var errors = req.validationErrors();
if (errors.length) {
res.json(errors);
return;
}
res.json({testparam: req.param('testparam')});
};
var app = new App(port, validation);
app.start();
function fail(body) {
assert.equal(body.length, 1);
assert.deepEqual(body[0].msg, errorMessage);
}
function pass(body) {
assert.deepEqual(body, {testparam: 123});
}
var tests = [
// Test URL param
async.apply(req, 'get', url + '/test', fail),
async.apply(req, 'get', url + '/123', pass),
async.apply(req, 'post', url + '/test', fail),
async.apply(req, 'post', url + '/123', pass),
// Test GET param and URL over GET param precedence
async.apply(req, 'get', url + '/test?testparam=gettest', fail),
async.apply(req, 'get', url + '/123?testparam=gettest', pass),
async.apply(req, 'get', url + '/123?testparam=gettest', pass),
async.apply(req, 'get', url + '/?testparam=test', fail),
async.apply(req, 'get', url + '/?testparam=123', pass),
// Test POST param and URL over GET over POST param precedence
async.apply(req, 'post', url + '/test?testparam=gettest', {json: {testparam: 123}}, fail),
async.apply(req, 'post', url + '/123?testparam=123', {json: {testparam: 'posttest'}}, pass),
async.apply(req, 'post', url + '/123?testparam=123', {json: {testparam: 'posttest'}}, pass),
async.apply(req, 'post', url + '/?testparam=test', {json: {testparam: 123}}, fail),
async.apply(req, 'post', url + '/?testparam=123', {json: {testparam: 'posttest'}}, pass),
async.apply(req, 'post', url + '/', {json: {testparam: 'test'}}, fail),
async.apply(req, 'post', url + '/', {json: {testparam: 123}}, pass)
];
async.parallel(tests, function(err) {
assert.ifError(err);
app.stop();
console.log('All %d tests passed.', tests.length);
});
// Sample app
var express = require('express');
var expressValidator = require('../../index');
function App(port, validation) {
this.app = null;
this.port = port;
this.validation = validation;
}
module.exports = App;
App.prototype.start = function() {
var self = this;
self.app = express.createServer();
self.app.use(express.bodyParser());
self.app.use(expressValidator);
self.app.get('/:testparam?', self.validation);
self.app.post('/:testparam?', self.validation);
self.app.listen(this.port);
};
App.prototype.stop = function() {
this.app.close();
};
var util = require('util'),
express = require('express'),
expressValidator = require('../../index'),
app = express.createServer();
app.use(express.bodyParser());
app.use(expressValidator);
app.post('/:urlparam', function(req, res) {
req.assert('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);
var request = require('request');
function check(assertion, cb) {
return function(err, res, body) {
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch (e) {
return cb(e);
}
}
assertion(body);
cb(null);
};
}
function req() {
var args = Array.prototype.slice.call(arguments);
var cb = args.pop();
var assertion = args.pop();
var method = args.shift();
args.push(check(assertion, cb));
request[method].apply(this, args);
}
module.exports = req;
var assert = require('assert');
var async = require('async');
var App = require('./helpers/app');
var req = require('./helpers/req');
var port = process.env.NODE_HTTP_PORT || 8888;
var url = 'http://localhost:' + port;
// Error descriptions can be selected in a mapped way
var validation = function(req, res) {
req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
var errors = req.validationErrors(true);
if (errors) {
res.json(errors);
return;
}
res.json({email: req.param('email')});
};
var app = new App(port, validation);
app.start();
function fail(body) {
assert.deepEqual(body.email.msg, 'valid email required');
}
function pass(body) {
assert.deepEqual(body, {email: 'test@example.com'});
}
var tests = [
async.apply(req, 'post', url + '/', {
json: {
email: 'test@example.com'
}
}, pass),
async.apply(req, 'post', url + '/', {
json: {
email: ''
}
}, fail)
];
async.parallel(tests, function(err) {
assert.ifError(err);
app.stop();
console.log('All %d tests passed.', tests.length);
});
var assert = require('assert');
var async = require('async');
var App = require('./helpers/app');
var req = require('./helpers/req');
var port = process.env.NODE_HTTP_PORT || 8888;
var url = 'http://localhost:' + port;
// Nested parameters are also supported
var validation = function(req, res) {
req.assert(['user', 'fields', 'email'], 'not empty').notEmpty();
req.assert(['user', 'fields', 'email'], 'valid email required').isEmail();
var errors = req.validationErrors();
if (errors) {
res.json(errors);
return;
}
res.json(req.body);
};
var app = new App(port, validation);
app.start();
function fail(body) {
assert.deepEqual(body[0].msg, 'not empty');
assert.deepEqual(body[1].msg, 'valid email required');
}
function pass(body) {
assert.deepEqual(body, {
user: {
fields: {
email: 'test@example.com'
}
}
});
}
var tests = [
async.apply(req, 'post', url + '/', {
json: {
user: {
fields: {
email: 'test@example.com'
}
}
}
}, pass),
async.apply(req, 'post', url + '/', {
json: {
user: {
fields: {
email: ''
}
}
}
}, fail)
];
async.parallel(tests, function(err) {
assert.ifError(err);
app.stop();
console.log('All %d tests passed.', tests.length);
});
+48
-2

@@ -49,3 +49,35 @@ /*

req.check = function(param, fail_msg) {
return validator.check(this.param(param), fail_msg);
var value;
// get value and param name for nested inputs like foo[bar][baz]
if (Array.isArray(param)) {
param.map(function(item) {
if(value === undefined) {
value = req.param(item);
} else {
value = value[item];
}
});
param = param.join('_');
} else {
value = this.param(param);
}
validator.error = function(msg) {
var error = {
param: param,
msg: msg,
value: value
};
if (req._validationErrors === undefined) {
req._validationErrors = [];
}
req._validationErrors.push(error);
if (req.onErrorCallback) {
req.onErrorCallback(msg);
}
}
return validator.check(value, fail_msg);
};

@@ -64,5 +96,19 @@

req.onValidationError = function(errback) {
validator.error = errback;
req.onErrorCallback = errback;
};
req.validationErrors = function(mapped) {
if (req._validationErrors === undefined) {
return false;
}
if (mapped) {
var errors = {};
req._validationErrors.forEach(function(err) {
errors[err.param] = err;
});
return errors;
}
return req._validationErrors;
}
req.filter = function(param) {

@@ -69,0 +115,0 @@ var self = this;

+10
-3

@@ -6,5 +6,6 @@ {

"contributors": [
"Chris O'Hara <cohara87@gmail.com>"
"Chris O'Hara <cohara87@gmail.com>",
"@orfaust"
],
"version": "0.1.3",
"version": "0.2.0",
"homepage": "https://github.com/ctavan/express-validator",

@@ -16,2 +17,5 @@ "repository": {

"main": "./index.js",
"scripts": {
"test": "make test"
},
"engines": {

@@ -21,5 +25,8 @@ "node": "*"

"dependencies": {
"validator": ">=0.2.8"
"validator": "~0.4.5"
},
"devDependencies": {
"async": "~0.1.18",
"express": "~2.5.9",
"request": "~2.9.153"
},

@@ -26,0 +33,0 @@ "keywords": [

+87
-12
# express-validator
[![Build Status](https://secure.travis-ci.org/ctavan/express-validator.png)](http://travis-ci.org/ctavan/express-validator)
An [express.js]( https://github.com/visionmedia/express ) middleware for

@@ -18,4 +20,5 @@ [node-validator]( https://github.com/chriso/node-validator ).

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

@@ -27,8 +30,2 @@

app.post('/:urlparam', function(req, res) {
var errors = [];
req.onValidationError(function(msg) {
console.log('Validation error: ' + msg);
errors.push(msg);
return this;
});

@@ -41,4 +38,5 @@ req.assert('postparam', 'Invalid postparam').notEmpty().isInt();

if (errors.length) {
res.send('There have been validation errors: ' + errors.join(', '), 500);
var errors = req.validationErrors();
if (errors) {
res.send('There have been validation errors: ' + util.inspect(errors), 500);
return;

@@ -63,6 +61,9 @@ }

$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1
There have been validation errors: Invalid urlparam
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: Invalid getparam, Invalid foo
There have been validation errors: [
{ param: 'getparam', msg: 'Invalid getparam', value: '1ab' },
{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
```

@@ -82,5 +83,78 @@

### Validation errors
You have two choices on how to get the validation errors:
```javascript
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:
```javascript
[
{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:
```javascript
{
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:
```html
<input name="user[fields][email]" />
```
Provide an array instead of a string:
```javascript
req.assert(['user', 'fields', 'email'], 'valid email required').isEmail();
var errors = req.validationErrors();
console.log(errors);
```
Output:
```javascript
[
{
param: "user_fields_email",
msg: "valid email required",
value: "<received input>"
}
]
```
## Changelog
### v0.2.0
- Added `validationErrors()` method (by @orfaust)
- Added support for nested form fields (by @orfaust)
- Added test cases
### v0.1.3

@@ -103,2 +177,3 @@ - Readme update

- Christoph Tavan <dev@tavan.de> - Wrap the gist in an npm package
- @orfaust - Add `validationErrors()` and nested field support

@@ -105,0 +180,0 @@ ## License

var express = require('express'),
expressValidator = require('../index.js'),
app = express.createServer();
app.use(express.bodyParser());
app.use(expressValidator);
app.post('/:urlparam', function(req, res) {
var errors = [];
req.onValidationError(function(msg) {
console.log('Validation error: ' + msg);
errors.push(msg);
return this;
});
req.assert('postparam', 'Invalid postparam').notEmpty().isInt();
req.assert('getparam', 'Invalid getparam').isInt();
req.assert('urlparam', 'Invalid urlparam').isAlpha();
req.sanitize('postparam').toBoolean();
if (errors.length) {
res.send('There have been validation errors: ' + errors.join(', '), 500);
return;
}
res.json({
urlparam: req.param('urlparam'),
getparam: req.param('getparam'),
postparam: req.param('postparam')
});
});
app.listen(8888);