New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

express-validation

Package Overview
Dependencies
Maintainers
2
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-validation - npm Package Compare versions

Comparing version 0.4.5 to 0.5.0

.eslintrc

137

lib/index.js
'use strict';
var Joi = require('joi');
var _ = require('lodash');
var util = require('util');
var assignIn = require('lodash/assignIn');
var find = require('lodash/find');
var defaults = require('lodash/defaults');
var isPlainObject = require('lodash/isPlainObject');
var ValidationError = require('./validation-error');
var ValidationError = function (errors, options) {
this.message = 'validation error';
Error.call(this);
this.errors = errors;
this.flatten = options.flatten;
this.status = options.status;
this.statusText = options.statusText;
};
util.inherits(ValidationError, Error);
ValidationError.prototype.toString = function () {
return JSON.stringify(this.toJSON());
};
ValidationError.prototype.toJSON = function () {
var response = {
status : this.status,
statusText : this.statusText,
errors : this.errors
};
if (this.flatten){
response = _.flatten(_.pluck(this.errors, 'messages'));
}
return response;
};
var defaultOptions = {

@@ -49,57 +22,18 @@ flatten: false,

exports = module.exports = function (schema) {
if (!schema) {
throw new Error("Please provide a validation schema");
}
if (!schema) throw new Error('Please provide a validation schema');
return function (req, res, next) {
var validate = function(current, request, schema, location, allowUnknown){
if (!request || !schema) {
return;
}
Joi.validate(request, schema, {context: request, allowUnknown : allowUnknown, abortEarly : false}, function(errors, value){
if (!errors || errors.details.length === 0) {
_.extend(request, value);
return;
}
_.each(errors.details, function(error){
var errorExists = _.find(current, function(item){
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
return;
});
if (!errorExists) {
current.push({ field : error.path, location : location, messages : [error.message], types:[error.type]});
}
}, errors);
});
};
var errors = [];
var pushErrors = function(errors, error){
if (error) {
errors.push(error);
}
};
// Set default options
var options = schema.options ? _.defaults({}, schema.options, globalOptions, defaultOptions) : _.defaults({}, globalOptions, defaultOptions);
var options = defaults({}, schema.options || {}, globalOptions, defaultOptions);
pushErrors(errors, validate(errors, req.headers, schema.headers, 'headers', options.allowUnknownHeaders));
pushErrors(errors, validate(errors, req.body, schema.body, 'body', options.allowUnknownBody));
pushErrors(errors, validate(errors, req.query, schema.query, 'query', options.allowUnknownQuery));
pushErrors(errors, validate(errors, _.extend({}, req.params), schema.params, 'params', options.allowUnknownParams));
pushErrors(errors, validate(errors, req.cookies, schema.cookies, 'cookies', options.allowUnknownCookies));
// NOTE: mutates `errors`
validate(errors, req.headers, schema.headers, 'headers', options.allowUnknownHeaders);
validate(errors, req.body, schema.body, 'body', options.allowUnknownBody);
validate(errors, req.query, schema.query, 'query', options.allowUnknownQuery);
validate(errors, isPlainObject(req.params) ? req.params : {}, schema.params, 'params', options.allowUnknownParams);
validate(errors, req.cookies, schema.cookies, 'cookies', options.allowUnknownCookies);
if (errors && errors.length === 0) {
return next();
}
if (errors && errors.length === 0) return next();

@@ -118,3 +52,44 @@ return next(new ValidationError(errors, options));

globalOptions = _.extend({}, globalOptions, opts);
globalOptions = defaults({}, globalOptions, opts);
};
/**
* validate checks the current `Request` for validations
* NOTE: mutates `request` in case the object is valid.
*/
function validate (errObj, request, schema, location, allowUnknown) {
if (!request || !schema) return;
var joiOptions = {
context: request,
allowUnknown: allowUnknown,
abortEarly: false
};
Joi.validate(request, schema, joiOptions, function (errors, value) {
if (!errors || errors.details.length === 0) {
assignIn(request, value); // joi responses are parsed into JSON
return;
}
errors.details.forEach(function (error) {
var errorExists = find(errObj, function (item) {
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
return;
});
if (!errorExists) {
errObj.push({
field: error.path,
location: location,
messages: [error.message],
types: [error.type]
});
}
});
});
};
{
"name": "express-validation",
"version": "0.4.5",
"version": "0.5.0",
"author": "Andrew Keig <andrew.keig@gmail.com>",
"description": "express-validation is a middleware that validates the body, params, query, headers and cookies of a request and returns a response with errors; if any of the configured validation rules fail.",
"homepage": "https://github.com/andrewkeig/express-validation",
"contributors": [{
"name": "Valerio Coltrè",
"email": "mister.gamer@gmail.com"
}],
"repository": {

@@ -12,17 +16,19 @@ "type": "git",

"dependencies": {
"joi": "^6.0.0",
"lodash": "^3.3.1"
"joi": "^7.1.0",
"lodash": "^4.0.0"
},
"devDependencies": {
"body-parser": "^1.3.0",
"cookie-parser": "^1.3.5",
"body-parser": "^1.14.2",
"cookie-parser": "^1.4.1",
"eslint": "^1.10.3",
"express": "~4.x",
"jshint": "^2.5.3",
"mocha": "*",
"should": "*",
"supertest": "*"
"jshint": "^2.9.1-rc3",
"mocha": "^2.3.4",
"should": "^8.1.1",
"supertest": "^1.1.0"
},
"license": "MIT",
"scripts": {
"pretest": "jshint lib",
"test": "jshint lib && mocha -R spec"
"pretest": "eslint lib",
"test": "eslint lib && mocha -R spec -b"
},

@@ -29,0 +35,0 @@ "engines": {

@@ -119,2 +119,27 @@ express-validation

## `req` objects gets parsed
When `Joi` validates the `body`, `params`, `query`, `headers` or `cookies` it returns it as Javascript Object.
Example without `express-validation`:
```
app.post('/login', function(req, res){
console.log(req.body); // => '{ "email": "user@domain", "password": "pwd" }'
res.json(200);
});
```
Example with `express-validation`:
```
var validate = require('express-validation');
var validation = require('./test/validation/login.js');
app.post('/login', validate(validation.login), function(req, res){
console.log(req.body); // => { email: "user@domain", password: "pwd" }
res.json(200);
});
```
The difference might seem very slight, but it's a big deal.
All parts of a `request` will be either parsed, or throw errors.
## Distinguish `Error`(s) from `ValidationError`(s)

@@ -230,2 +255,4 @@ Since 0.4.0 `express-validation` calls `next()` with a `ValidationError`, a specific type of `Error`.

0.5.0: `req` objects gets parsed. `Joi` validates the `body`, `params`, `query`, `headers` or `cookies` and returns a Javascript Object.
0.4.5: support for `Joi.ref` inside arrays, refer to #17 for an example

@@ -253,7 +280,8 @@

## Contributors
* Christian Holm https://github.com/holm
* Iheanyi Ekechukwu https://github.com/iheanyi
* Aymeric Beaumet https://github.com/aymericbeaumet
* Valerio Coltrè https://github.com/mrgamer
* Valerio Coltrè https://github.com/colthreepv
* gdw2 https://github.com/gdw2
* Robert Barbey https://github.com/rbarbey
* Stefan Lapers https://github.com/slapers
'use strict';
var express = require('express')
, validate = require('../lib/index')
, http = require('http')
, validation = require('./validation')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, app = express()
var express = require('express');
var validate = require('../lib/index');
var http = require('http');
var validation = require('./validation');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
app.use(bodyParser.json())
app.use(cookieParser())
app.use(bodyParser.json());
app.use(cookieParser());
app.set('port', 3000);
app.post('/login', validate(validation.login), function(req, res){
res.json(200);
});
// generates a response function sending back to user the specified req[key]
function respondWith (key) {
return function (req, res) {
res.json(req[key]);
};
}
app.get('/user', validate(validation.user.get), function(req, res){
res.json(200);
});
function respond200 (req, res) {
res.json(200);
}
app.get('/account/:id', validate(validation.account), function(req, res){
res.json(200);
});
app.post('/login', validate(validation.login), respond200);
app.get('/user', validate(validation.user.get), respond200);
app.get('/search', validate(validation.search), respond200);
app.put('/user/:id', validate(validation.user.put), respond200);
app.post('/register', validate(validation.register.post), respond200);
app.post('/options', validate(validation.options), respond200);
app.get('/account/:id', validate(validation.account), respondWith('params'));
app.post('/defaults', validate(validation.defaults), respondWith('body'));
app.get('/search', validate(validation.search), function(req, res){
res.json(200);
});
app.get('/parsing/params/:id?', validate(validation.parsing.params), respondWith('params'));
app.get('/parsing/query', validate(validation.parsing.query), respondWith('query'));
app.post('/parsing/body', validate(validation.parsing.body), respondWith('body'));
app.get('/parsing/headers', validate(validation.parsing.headers), respondWith('headers'));
app.get('/parsing/cookies', validate(validation.parsing.cookies), respondWith('cookies'));
app.put('/user/:id', validate(validation.user.put), function(req, res){
res.json(200);
});
app.post('/logout', validate(validation.logout), respond200);
app.post('/array', validate(validation.array), respond200);
app.post('/register', validate(validation.register.post), function(req, res){
res.json(200);
});
app.post('/options', validate(validation.options), function(req, res){
res.json(200);
})
app.post('/defaults', validate(validation.defaults), function(req, res) {
res.json(req.body);
})
app.post('/logout', validate(validation.logout), function(req, res){
res.json(200)
})
app.post('/array', validate(validation.array), function(req, res) {
res.json(200);
});
app.use(function(err, req, res, next){
// default errorhandler for express-validation
app.use(function (err, req, res, next) {
res.status(400).json(err);

@@ -57,0 +48,0 @@ });

@@ -1,15 +0,14 @@

var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require("supertest");
require('should');
var app = require('./app');
var request = require('supertest');
describe('for validating array values', function() {
describe('when the schema contains an array reference', function() {
it('should return a 200 ok response', function(done) {
describe('for validating array values', function () {
describe('when the schema contains an array reference', function () {
it('should return a 200 ok response', function (done) {
request(app)
.post('/array')
.send({numbers: [1, 2, 3], validate_numbers: [1, 2]})
.send({ numbers: [1, 2, 3], validate_numbers: [1, 2] })
.expect(200)
.end(function(err, res) {
if(err) {
.end(function (err, res) {
if (err) {
return done(err);

@@ -22,10 +21,10 @@ }

describe('when the schema contains an invalid array reference', function() {
it('should return a 400 response', function(done) {
describe('when the schema contains an invalid array reference', function () {
it('should return a 400 response', function (done) {
request(app)
.post('/array')
.send({numbers: [1, 2, 3], validate_numbers:[4, 5]})
.send({ numbers: [1, 2, 3], validate_numbers:[4, 5] })
.expect(400)
.end(function(err, res) {
if(err) {
.end(function (err, res) {
if (err) {
return done(err);

@@ -32,0 +31,0 @@ }

'use strict';
require('should');
var app = require('./app');
var request = require('supertest');
var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require('supertest');
describe('validate body', function () {

@@ -12,7 +10,7 @@

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: "12356"
email: 'andrew.keig@gmail.com',
password: '12356'
};

@@ -26,6 +24,6 @@

var response = JSON.parse(res.text);
response.should.equal(200)
response.should.equal(200);
done();
});
});
});
});

@@ -35,7 +33,7 @@

it('should return a 400 ok response and a single error', function(done){
it('should return a 400 ok response and a single error', function (done) {
var login = {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
};

@@ -52,3 +50,3 @@

});
});
});
});

@@ -58,7 +56,7 @@

it('should return a 400 ok response and a single error', function(done){
it('should return a 400 ok response and a single error', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: ""
email: 'andrew.keig@gmail.com',
password: ''
};

@@ -77,3 +75,3 @@

});
});
});
});

@@ -83,7 +81,7 @@

it('should return a 400 ok response and two errors', function(done){
it('should return a 400 ok response and two errors', function (done) {
var login = {
email: "",
password: ""
email: '',
password: ''
};

@@ -104,3 +102,3 @@

});
});
});
});

@@ -110,8 +108,8 @@

it('should return a 400 ok response and one error', function(done){
it('should return a 400 ok response and one error', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: "12356",
token: "1234"
email: 'andrew.keig@gmail.com',
password: '12356',
token: '1234'
};

@@ -130,4 +128,4 @@

});
});
});
});
});
'use strict';
require('should');
var app = require('./app');
var request = require('supertest');
var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require('supertest');
describe('validate cookies', function () {

@@ -12,3 +10,3 @@

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {

@@ -22,6 +20,6 @@ request(app)

var response = JSON.parse(res.text);
response.should.equal(200)
response.should.equal(200);
done();
});
});
});
});

@@ -31,3 +29,3 @@

it('should return a 400 ok response and a single error', function(done){
it('should return a 400 ok response and a single error', function (done) {

@@ -44,3 +42,3 @@ request(app)

});
});
});
});

@@ -50,3 +48,3 @@

it('should return a 400 ok response and a single error', function(done){
it('should return a 400 ok response and a single error', function (done) {

@@ -65,3 +63,3 @@ request(app)

});
});
});
});

@@ -71,3 +69,3 @@

it('should return a 400 ok response and two errors', function(done){
it('should return a 400 ok response and two errors', function (done) {

@@ -87,3 +85,3 @@ request(app)

});
});
});
});

@@ -93,3 +91,3 @@

it('should return a 400 ok response and one error', function(done){
it('should return a 400 ok response and one error', function (done) {

@@ -108,4 +106,4 @@ request(app)

});
});
});
});
});
'use strict';
require('should');
var app = require('./app');
var request = require('supertest');
var validation = require('../lib/index')
, app = require('./app')
, should = require('should')
, request = require('supertest');
describe('set default values', function() {
describe('when the values are missing', function() {
describe('set default values', function () {
describe('when the values are missing', function () {
// Expect default values to be set
it('should return the request with default values', function(done) {
it('should return the request with default values', function (done) {
request(app)
.post('/defaults')
.send({firstname: "Jane", lastname: "Doe"})
.send({ firstname: 'Jane', lastname: 'Doe' })
.expect(200)
.end(function (err, res) {
var response = JSON.parse(res.text);
response.username.should.equal("jane-doe");
response.username.should.equal('jane-doe');
done();

@@ -24,2 +22,2 @@ });

})
});
'use strict';
require('should');
var validation = require('../lib/index');
var validation = require('../lib/index')
, should = require('should');
describe('when library throws an error', function () {

@@ -12,4 +11,4 @@

body: {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
}

@@ -30,4 +29,4 @@ };

body: {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
}

@@ -48,4 +47,4 @@ };

body: {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
}

@@ -52,0 +51,0 @@ };

@@ -11,3 +11,3 @@ 'use strict';

describe('when the request contains a valid header', function () {
it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {

@@ -21,10 +21,10 @@ request(app)

var response = JSON.parse(res.text);
response.should.equal(200)
response.should.equal(200);
done();
});
});
});
});
describe('when the request contains an invalid header', function () {
it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {

@@ -43,4 +43,4 @@ request(app)

});
});
});
});
});

@@ -12,7 +12,7 @@ 'use strict';

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: "12356"
email: 'andrew.keig@gmail.com',
password: '12356'
};

@@ -28,6 +28,6 @@

var response = JSON.parse(res.text);
response.should.equal(200)
response.should.equal(200);
done();
});
});
});
});

@@ -37,7 +37,7 @@

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: "12356"
email: 'andrew.keig@gmail.com',
password: '12356'
};

@@ -56,6 +56,6 @@

response.errors[0].types.length.should.equal(1);
response.errors[0].field.should.equal('id')
response.errors[0].field.should.equal('id');
done();
});
});
});
});

@@ -65,7 +65,7 @@

it('should return a 400 ok response and two errors', function(done){
it('should return a 400 ok response and two errors', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: ""
email: 'andrew.keig@gmail.com',
password: ''
};

@@ -83,6 +83,6 @@

response.errors[0].messages.length.should.equal(2);
response.errors[0].field.should.equal('password')
response.errors[0].field.should.equal('password');
done();
});
});
});
});

@@ -92,7 +92,7 @@

it('should return a 400 ok response and two errors', function(done){
it('should return a 400 ok response and two errors', function (done) {
var login = {
email: "andrew.keig@gmail.com",
password: "32323432"
email: 'andrew.keig@gmail.com',
password: '32323432'
};

@@ -110,7 +110,7 @@

response.errors[0].messages.length.should.equal(1);
response.errors[0].field.should.equal('accesstoken')
response.errors[0].field.should.equal('accesstoken');
done();
});
});
});
});
});

@@ -15,4 +15,4 @@ 'use strict';

var login = {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
};

@@ -50,3 +50,3 @@

});
})
});
});

@@ -67,4 +67,4 @@

body: {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
}

@@ -94,4 +94,4 @@ };

body: {
email: "andrew.keiggmail.com",
password: "12356"
email: 'andrew.keiggmail.com',
password: '12356'
}

@@ -98,0 +98,0 @@ };

@@ -12,3 +12,3 @@ 'use strict';

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {
request(app)

@@ -18,7 +18,6 @@ .get('/account/1')

.end(function (err, res) {
var response = JSON.parse(res.text);
response.should.equal(200);
res.body.id.should.equal(1);
done();
});
});
});
});

@@ -28,3 +27,3 @@

it('should return a 400 response', function(done){
it('should return a 400 response', function (done) {
request(app)

@@ -34,8 +33,7 @@ .get('/account/a')

.end(function (err, res) {
var response = JSON.parse(res.text);
response.errors.length.should.equal(1);
res.body.errors.length.should.equal(1);
done();
});
});
});
});
});

@@ -12,3 +12,3 @@ 'use strict';

it('should return a 200 ok response', function(done){
it('should return a 200 ok response', function (done) {
request(app)

@@ -22,3 +22,3 @@ .get('/search?q=true')

});
});
});
});

@@ -28,3 +28,3 @@

it('should return a 400 response', function(done){
it('should return a 400 response', function (done) {
request(app)

@@ -38,4 +38,4 @@ .get('/search?q=')

});
});
});
});
});

@@ -12,7 +12,7 @@ 'use strict';

it('should return a 400 ok response and two errors flattened', function(done){
it('should return a 400 ok response and two errors flattened', function (done) {
var register = {
email: "",
password: ""
email: '',
password: ''
};

@@ -29,4 +29,4 @@

});
});
});
});
});

@@ -1,2 +0,2 @@

var Joi = require("joi");
var Joi = require('joi');

@@ -9,2 +9,2 @@

}
}
};
var Joi = require('joi');
var generateUsername = function(context) {
var generateUsername = function (context) {
return context.firstname.toLowerCase() + '-' + context.lastname.toLowerCase();
}
};
generateUsername.description = "generated username";
generateUsername.description = 'generated username';
module.exports = {

@@ -16,5 +16,5 @@ body: {

registered: Joi.boolean().default(true),
type: Joi.string().when('registered', {is: true, then: Joi.default('registered'), otherwise: Joi.default('unregistered')}),
type: Joi.string().when('registered', { is: true, then: Joi.default('registered'), otherwise: Joi.default('unregistered') }),
values: Joi.array().default(['1'])
}
}
};
'use strict';
exports.account = require('./account');
exports.array = require('./array');
exports.defaults = require('./defaults');
exports.login = require('./login');
exports.logout = require('./logout');
exports.options = require('./options');
exports.parsing = require('./parsing');
exports.register = require('./register');
exports.search = require('./search');
exports.user = require('./user');
exports.search = require('./search');
exports.account = require('./account');
exports.register = require('./register');
exports.options = require('./options');
exports.logout = require('./logout');
exports.defaults = require('./defaults');
exports.array = require('./array');

@@ -11,2 +11,2 @@ 'use strict';

}
}
};
'use strict';
var Joi = require('joi');
module.exports.post = {
options : { flatten : true },
options: { flatten: true },
body: {

@@ -8,0 +7,0 @@ email: Joi.string().required().email(),

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc