Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

express-validator

Package Overview
Dependencies
Maintainers
3
Versions
121
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 6.9.2 to 6.10.0

docs/faq.md

4

docs/api-check.md

@@ -55,3 +55,3 @@ ---

> _Returns:_ an array of validation chains
> _Returns:_ an array of validation chains and `{ run: (req) => Promise<unknown[]> }`

@@ -64,3 +64,3 @@ ## `oneOf(validationChains[, message])`

> _Returns:_ a middleware instance
> _Returns:_ a middleware instance and `{ run: (req) => Promise<void> }`

@@ -67,0 +67,0 @@ Creates a middleware instance that will ensure at least one of the given chains passes the validation.

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

> **For a complete list of standard sanitizers and their options**,
> please check [validator.js' docs](https://github.com/chriso/validator.js#sanitizers).
> please check [validator.js' docs](https://github.com/validatorjs/validator.js#sanitizers).
> **Note:** Since validator.js only accepts `string` as input, any value (including arrays and objects) that needs to be sanitized by a Standard Sanitizer [is first converted to such type](faq.md#why-arrays-are-not-validatedsanitized-correctly).
## Additional methods

@@ -32,0 +34,0 @@

@@ -24,4 +24,6 @@ ---

> **For a complete list of standard validators and their options**,
> please check [validator.js' docs](https://github.com/chriso/validator.js#validators).
> please check [validator.js' docs](https://github.com/validatorjs/validator.js#validators).
> **Note:** Since validator.js only accepts `string` as input, any value (including arrays and objects) that needs to be validated by a Standard Validator [is first converted to such type](faq.md#why-arrays-are-not-validatedsanitized-correctly).
## Sanitization Chain API

@@ -155,2 +157,11 @@

### `.isObject(options)`
- `options` _(optional)_: an object which accepts the following options:
- `strict`: If set to `false` the validation passes also for `array` and `null` types (defaults to `true`).
> _Returns:_ the current validation chain instance
Adds a validator to check if a value is an object.
### `.isString()`

@@ -182,2 +193,13 @@

> **Note:** This is not intended to check that the length of an array is greater than zero, as `.notEmpty()` will only validate the first element of it.
> To require a minimum array length use `.isArray({ min: 1 })`.
>
> ```js
> // weekdays: ['sunday', 'monday']
> check('weekdays').notEmpty(); // Passes validation
>
> // names: ['', 'John']
> check('names').notEmpty(); // Does not pass validation because names[0] is empty.
> ```
### `.optional(options)`

@@ -184,0 +206,0 @@

@@ -85,3 +85,7 @@ ---

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js
const { validationResult } = require('express-validator');
app.post('/create-user', yourValidationChains, (req, res, next) => {

@@ -103,2 +107,24 @@ const errorFormatter = ({ location, msg, param, value, nestedErrors }) => {

<!--TypeScript-->
```typescript
import { validationResult, ValidationError } from 'express-validator';
app.post('/create-user', yourValidationChains, (req, res, next) => {
const errorFormatter = ({ location, msg, param, value, nestedErrors }: ValidationError) => {
// Build your resulting errors however you want! String, object, whatever - it works!
return `${location}[${param}]: ${msg}`;
};
const result = validationResult(req).formatWith(errorFormatter);
if (!result.isEmpty()) {
// Response will contain something like
// { errors: [ "body[password]: must be at least 10 chars long" ] }
return res.json({ errors: result.array() });
}
// Handle your request as if no errors happened
});
```
<!--END_DOCUSAURUS_CODE_TABS-->
### `.array([options])`

@@ -105,0 +131,0 @@

@@ -7,3 +7,3 @@ ---

Although express-validator offers plenty of handy validators and sanitizers through its underlying
dependency [validator.js](https://github.com/chriso/validator.js), it doesn't always suffice when
dependency [validator.js](https://github.com/validatorjs/validator.js), it doesn't always suffice when
building your application.

@@ -25,2 +25,5 @@

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js

@@ -44,2 +47,22 @@ const { body } = require('express-validator');

<!--TypeScript-->
```js
import { body, CustomValidator } from 'express-validator';
// This allows you to reuse the validator
const isValidUser: CustomValidator = value => {
return User.findUserByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
};
app.post('/user', body('email').custom(isValidUser), (req, res) => {
// Handle the request
});
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Example: checking if password confirmation matches password

@@ -76,2 +99,5 @@

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js

@@ -90,1 +116,17 @@ const { param } = require('express-validator');

```
<!--TypeScript-->
```typescript
import { param } from 'express-validator';
// This allows you to reuse the validator
const toObjectId: CustomSanitizer = value => {
return ObjectId(value);
};
app.post('/object/:id', param('id').customSanitizer(toObjectId), (req, res) => {
// Handle the request
});
```
<!--END_DOCUSAURUS_CODE_TABS-->

@@ -10,4 +10,4 @@ ---

You can, however, give control of running these validations to your own middleware/route handler.
This is possible with the use of the declarative method `run(req)`, available on both
[validation chain](api-validation-chain.md#runreq-options) and [sanitization chains](api-sanitization-chain.md#runreq).
This is possible with the use of the declarative method `run(req)`, available on
[validation chain](api-validation-chain.md#runreq-options), [sanitization chain](api-sanitization-chain.md#runreq), [`checkSchema`](api-check.md#checkschemaschema) and [`oneOf`](api-check.md#oneofvalidationchains-message).

@@ -18,3 +18,8 @@ Check the examples below to understand how this method can help you:

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js
const express = require('express');
const { validateResult, ValidationChain } = require('express-validator');
// can be reused by many routes

@@ -54,2 +59,43 @@

<!--TypeScript-->
```typescript
import express from 'express';
import { validateResult, ValidationChain } from 'express-validator';
// can be reused by many routes
// parallel processing
const validate = (validations: ValidationChain[]) => {
return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
await Promise.all(validations.map(validation => validation.run(req)));
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
res.status(400).json({ errors: errors.array() });
};
};
// sequential processing, stops running validations chain if the previous one have failed.
const validate = (validations: ValidationChain[]) => {
return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
res.status(400).json({ errors: errors.array() });
};
};
```
<!--END_DOCUSAURUS_CODE_TABS-->
```js

@@ -56,0 +102,0 @@ app.post('/api/create-user', validate([

@@ -9,3 +9,3 @@ ---

[validator.js provides a handful of sanitizers](https://github.com/chriso/validator.js#sanitizers)
[validator.js provides a handful of sanitizers](https://github.com/validatorjs/validator.js#sanitizers)
that can be used to take care of the data that comes in.

@@ -12,0 +12,0 @@

@@ -16,3 +16,3 @@ ---

const express = require('express');
const { check, sanitize } = require('express-validator');
const { check } = require('express-validator');

@@ -25,3 +25,3 @@ const app = express();

check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt(),
check('addresses.*.number').toInt(),
(req, res) => {

@@ -28,0 +28,0 @@ // Handle the request

@@ -7,3 +7,3 @@ ---

express-validator is a set of [express.js](http://expressjs.com/) middlewares that wraps
[validator.js](https://github.com/chriso/validator.js) validator and sanitizer functions.
[validator.js](https://github.com/validatorjs/validator.js) validator and sanitizer functions.

@@ -25,2 +25,5 @@ ## Installation

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js

@@ -39,4 +42,24 @@ const express = require('express');

<!--TypeScript-->
```typescript
import express from 'express';
const app = express();
app.use(express.json());
app.post('/user', (req: express.Request, res: express.Response) => {
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user));
});
```
<!--END_DOCUSAURUS_CODE_TABS-->
Then, you'll want to make sure that you validate the input and report any errors before creating the user:
<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->
```js

@@ -67,2 +90,31 @@ // ...rest of the initial code omitted for simplicity.

<!--TypeScript-->
```typescript
// ...rest of the initial code omitted for simplicity.
import { body, validationResult } from 'express-validator';
app.post(
'/user',
// username must be an email
body('username').isEmail(),
// password must be at least 5 chars long
body('password').isLength({ min: 5 }),
(req: express.Request, res: express.Response) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user));
},
);
```
<!--END_DOCUSAURUS_CODE_TABS-->
_Voila!_ Now, whenever a request that includes invalid `username` or `password` fields

@@ -84,3 +136,3 @@ is submitted, your server will respond like this:

For all the available validators in express-validator (just like its options),
take a look at validator.js docs [here](https://github.com/chriso/validator.js#validators).
take a look at validator.js docs [here](https://github.com/validatorjs/validator.js#validators).

@@ -87,0 +139,0 @@ ## What's next

@@ -10,3 +10,3 @@ {

],
"version": "6.9.2",
"version": "6.10.0",
"homepage": "https://express-validator.github.io",

@@ -50,14 +50,14 @@ "license": "MIT",

"devDependencies": {
"@types/jest": "^26.0.15",
"@types/lodash": "^4.14.165",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
"@types/jest": "^26.0.20",
"@types/lodash": "^4.14.168",
"@typescript-eslint/eslint-plugin": "^4.14.0",
"@typescript-eslint/parser": "^4.14.0",
"coveralls": "^3.1.0",
"docusaurus": "^1.14.6",
"eslint": "^7.14.0",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-import": "^2.21.2",
"eslint-plugin-prettier": "^3.1.4",
"eslint": "^7.18.0",
"eslint-config-prettier": "^7.1.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.0",
"prettier": "^2.2.1",
"ts-jest": "^26.4.4",

@@ -64,0 +64,0 @@ "typescript": "^3.9.7"

@@ -9,3 +9,3 @@ # express-validator

An [express.js](https://github.com/visionmedia/express) middleware for
[validator](https://github.com/chriso/validator.js).
[validator](https://github.com/validatorjs/validator.js).

@@ -12,0 +12,0 @@ - [Installation](#installation)

import { ReadonlyContext } from './context';
export interface Request {
[k: string]: any;
body?: any;
cookies?: Record<string, any>;
headers?: Record<string, any>;
params?: Record<string, any>;
query?: Record<string, any>;
}
export declare type Middleware = (req: Request, res: any, next: (err?: any) => void) => void;
export declare type Location = 'body' | 'cookies' | 'headers' | 'params' | 'query';

@@ -33,10 +42,2 @@ export declare type Meta = {

};
export interface Request {
[k: string]: any;
body?: any;
cookies?: Record<string, any>;
headers?: Record<string, any>;
params?: Record<string, any>;
query?: Record<string, any>;
}
export declare const contextsKey = "express-validator#contexts";

@@ -46,4 +47,3 @@ export interface InternalRequest extends Request {

}
export declare type Middleware = (req: Request, res: any, next: (err?: any) => void) => void;
export declare class ValidationHalt extends Error {
}

@@ -23,2 +23,5 @@ import { CustomValidator } from '../base';

}): Chain;
isObject(options?: {
strict?: boolean;
}): Chain;
isString(): Chain;

@@ -38,3 +41,3 @@ notEmpty(options?: Options.IsEmptyOptions): Chain;

isBIC(): Chain;
isBoolean(): Chain;
isBoolean(options?: Options.IsBooleanOptions): Chain;
isBtcAddress(): Chain;

@@ -41,0 +44,0 @@ isByteLength(options: Options.MinMaxOptions): Chain;

@@ -50,2 +50,6 @@ "use strict";

}
isObject(options = { strict: true }) {
return this.custom(value => typeof value === 'object' &&
(options.strict ? value !== null && !Array.isArray(value) : true));
}
isString() {

@@ -96,3 +100,8 @@ return this.custom(value => typeof value === 'string');

}
isBoolean() {
isBoolean(options) {
if (options === null || options === void 0 ? void 0 : options.strict) {
return this.custom(value => {
return value === true || value === false;
});
}
return this.addStandardValidation(validator.isBoolean);

@@ -99,0 +108,0 @@ }

@@ -16,2 +16,5 @@ import { CustomValidator, DynamicMessageCreator } from '../base';

}): Return;
isObject(options?: {
strict?: boolean;
}): Return;
isString(): Return;

@@ -30,3 +33,3 @@ notEmpty(options?: Options.IsEmptyOptions): Return;

isBIC(): Return;
isBoolean(): Return;
isBoolean(options?: Options.IsBooleanOptions): Return;
isBtcAddress(): Return;

@@ -33,0 +36,0 @@ isByteLength(options: Options.MinMaxExtendedOptions): Return;

@@ -6,3 +6,7 @@ import { ValidationChain } from '../chain';

}) => any;
export declare function oneOf(chains: (ValidationChain | ValidationChain[])[], message?: OneOfCustomMessageBuilder): Middleware;
export declare function oneOf(chains: (ValidationChain | ValidationChain[])[], message?: any): Middleware;
export declare function oneOf(chains: (ValidationChain | ValidationChain[])[], message?: OneOfCustomMessageBuilder): Middleware & {
run: (req: Request) => Promise<void>;
};
export declare function oneOf(chains: (ValidationChain | ValidationChain[])[], message?: any): Middleware & {
run: (req: Request) => Promise<void>;
};

@@ -10,3 +10,3 @@ "use strict";

function oneOf(chains, message) {
return async (req, _res, next) => {
const middleware = async (req, _res, next) => {
const surrogateContext = new context_builder_1.ContextBuilder().addItem(dummyItem).build();

@@ -43,3 +43,11 @@ // Run each group of chains in parallel, and within each group, run each chain in parallel too.

};
const run = async (req) => {
return new Promise((resolve, reject) => {
middleware(req, {}, (e) => {
e ? reject(e) : resolve();
});
});
};
return Object.assign(middleware, { run });
}
exports.oneOf = oneOf;
import { Sanitizers } from '../chain/sanitizers';
import { Validators } from '../chain/validators';
import { DynamicMessageCreator, Location } from '../base';
import { DynamicMessageCreator, Location, Request } from '../base';
import { ValidationChain } from '../chain';
import { Optional } from '../context';

@@ -44,3 +45,5 @@ declare type ValidatorSchemaOptions<K extends keyof Validators<any>> = true | {

export declare type ValidationSchema = Schema;
export declare function checkSchema(schema: Schema, defaultLocations?: Location[]): import("../chain").ValidationChain[];
export declare function checkSchema(schema: Schema, defaultLocations?: Location[]): ValidationChain[] & {
run: (req: Request) => Promise<unknown[]>;
};
export {};

@@ -9,3 +9,3 @@ "use strict";

function checkSchema(schema, defaultLocations = validLocations) {
return Object.keys(schema).map(field => {
const chains = Object.keys(schema).map(field => {
const config = schema[field];

@@ -41,2 +41,6 @@ const chain = check_1.check(field, ensureLocations(config, defaultLocations), config.errorMessage);

});
const run = async (req) => {
return await Promise.all(chains.map(chain => chain.run(req)));
};
return Object.assign(chains, { run });
}

@@ -43,0 +47,0 @@ exports.checkSchema = checkSchema;

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

export declare type URLProtocol = 'http' | 'https' | 'ftp';
export declare type URLProtocol = 'http' | 'https' | 'ftp' | string;
export declare type UUIDVersion = 3 | 4 | 5 | '3' | '4' | '5' | 'all';

@@ -45,2 +45,11 @@ export declare type IPVersion = 4 | 6;

* {
* strict: false
* }
*/
export interface IsBooleanOptions {
strict?: boolean;
}
/**
* defaults to
* {
* symbol: '$',

@@ -47,0 +56,0 @@ * require_symbol: false,

@@ -22,2 +22,5 @@ "use strict";

else if (value && typeof value === 'object' && value.toString) {
if (typeof value.toString !== 'function') {
return Object.getPrototypeOf(value).toString.call(value);
}
return value.toString();

@@ -24,0 +27,0 @@ }

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