• Stars
    star
    393
  • Rank 109,518 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

express-validation is an express middleware that validates a request and returns a response with errors; if any of the configured validation rules fail.

express-validation

Build Status npm module Current Version airbnb-style Coverage Status npm downloads Known Vulnerabilities

express-validation is an express middleware that validates a request and returns a response with errors; if any of the configured validation rules fail.

We use joi to define validation rules. We have a hard dependency on Joi in order to avoid compatibility issues with Joi releases. We are using snyk, which should help with this process.

Currently support Joi v17.x.x

Parameter types

We support validating the following parameter types:

  • headers
  • params (path)
  • query
  • cookies
  • signedCookies
  • body

Install

Install with npm:

npm i express-validation --save

Install with yarn:

yarn add express-validation

Example

In order to setup and use express-validation consider the following simple express application. It has a single route; configured to use the express-validation middleware function validate; it accepts as input loginValidation; which defines validation rules for this route.

const express = require('express')
const bodyParser = require('body-parser')
const { validate, ValidationError, Joi } = require('express-validation')

const loginValidation = {
  body: Joi.object({
    email: Joi.string()
      .email()
      .required(),
    password: Joi.string()
      .regex(/[a-zA-Z0-9]{3,30}/)
      .required(),
  }),
}

const app = express();
app.use(bodyParser.json())

app.post('/login', validate(loginValidation, {}, {}), (req, res) => {
  res.json(200)
})

app.use(function(err, req, res, next) {
  if (err instanceof ValidationError) {
    return res.status(err.statusCode).json(err)
  }

  return res.status(500).json(err)
})

app.listen(3000)

We have defined two rules email and password. They are encapsulated inside body; which is important; as this defines their location within the request.

We also need to setup an express global error handler, express-validation will pass errors to this handler. We can check within the handler for errors of type validationError distinguishing validation errors from other types of error.

Errors

express-validation, by default will return errors in the following format, an object details keyed by parameter, each containing an array of errors in joi format.

{
      "name": "ValidationError",
      "message": "Validation Failed",
      "statusCode": 400,
      "error": "Bad Request",
      "details": {
        "body": [
          {
            "message": "\"password\" is not allowed to be empty",
            "path": [
              "password"
            ],
            "type": "string.empty",
            "context": {
              "label": "password",
              "value": "",
              "key": "password"
            }
          }
        ]
      }
    }

We support other simpler formats via configuration

  • keyByField, flattens the error details object to a list of messages, keyed by field name
{
  "name": "ValidationError",
  "message": "Validation Failed",
  "statusCode": 400,
  "error": "Bad Request",
  "details": [
    { "accesstoken": "\"accesstoken\" is not allowed to be empty" },
    { "password": "\"password\" is not allowed to be empty" }
  ]
}

API

express-validation exposes the following api:

validate(schema, [options], [joiOptions]) => [validationError]

The exported validate function takes a schema object and two optional arguments, options and joiOptions and returns a validationError instance if schema contains errors.

schema (Object)

Default: {}

Includes validition rules, defined using joi, the rules are keyed by the following parameter types:

  • headers
  • params (path)
  • query
  • cookies
  • signedCookies
  • body

options (Object)

Default: { context: false, statusCode: 400, keyByField: false }

Options, used by express-validation:

  • context, grants Joi access to the request object. This allows you to:
    • reference other parts of the request in your validations, see Joi.ref
    • specify default values, see Joi.default
    • will also cast values, e.g. strings to integer
    • default { context: false }
  • statusCode, defaults to 400, this will also set the error message via nodes status codes
    • default { statusCode: 400 }
  • keyByField, flattens the error details object to a list of messages, keyed by field name

joiOptions (Object)

Default: {}

Options, used by joi, see Joi options, note:

ValidationError

We expose a custom error; ValidationError, use this in you global express error handler to distinguish validation errors from other types of error.

Joi

We also expose the version of Joi we have as a dependency, in order to avoid compatibility issues with other versions of Joi.

Examples

For more information on how to use express-validation please see the following examples:

abortEarly

abortEarly.test.js

You can return multiple errors, not just the first encountered, by setting, the joi option abortEarly: false

context

context.test.js

Enabling the context in options, allows you to reference other parts of the request in your validation.

defaults

default.test.js

You can specify joi default values in your schema.

License

This work is licensed under the MIT License (see the LICENSE file).

https://github.com/AndrewKeig/express-validation/blob/master/LICENSE

More Repositories

1

protractor-cucumber

protractor-cucumber
JavaScript
73
star
2

react-speech

React component for the web speech api
JavaScript
71
star
3

advanced-express-application-development

Source code for book: Advanced Express Web Application Development
JavaScript
59
star
4

node-plates

a node.js boilerplate using express, socket.io, mongooose, jquery.mobile & html 5 mobile/web application.
JavaScript
29
star
5

rabbitmq-messaging-application-development

Source code for book: Instant RabbitMQ Messaging Application Development How-to
JavaScript
24
star
6

passport-azure-oauth2

Passport strategy for authenticating with Azure OAuth 2.0 API.
JavaScript
15
star
7

angular-sir-trevor

Sir trevor as a service in Angular
11
star
8

grunt-mongoimport

grunt task wraps up the mongoimport command
JavaScript
11
star
9

supertest-postman

This project will take a postman collection v2 file and generate supertest tests.
JavaScript
10
star
10

wdio-cucumber-reporter

A WebdriverIO plugin. Report results in cucumber format.
JavaScript
8
star
11

grunt-jscoverage

Grunt task to parse your source code and generate an instrumented version allowing testing tools to generate code coverage reports
JavaScript
7
star
12

joi-phone

validates that the value is a valid international phone number complying to E.164 numbering format
JavaScript
7
star
13

express-swagger

JavaScript
6
star
14

super-grass

Monitoring solution for Apis, RabbitMQ, MongoDb and Redis
JavaScript
6
star
15

express-validation-swagger

JavaScript
6
star
16

the-internet-of-things-rabbitmq-mqtt

The Internet of things, with RabbitMQ, Node.js, MQTT and AMQP
JavaScript
5
star
17

joi-contrib

JavaScript
5
star
18

session-konphyg

Configuring session stores for the node.js express framework; session-konphyg uses konphyg to provide cascading configuration to support multiple environments
JavaScript
4
star
19

dust-down

A node.js command line tool which will compile all dust.js templates in a given directory
JavaScript
4
star
20

discographql

TypeScript
3
star
21

nosoco

Pushing couchdb changes to a web client via node.js/socket.io
JavaScript
3
star
22

infobip-sms

An infobip sms service; currently the only endpoint implemented is sendsms.
JavaScript
3
star
23

nft-pixels

JavaScript
2
star
24

swagger-fixtures

swagger-fixtures, generate a test fixture from the definitions, property examples in your swagger document.
JavaScript
2
star
25

supermyx

supermyx is a highly oppionated rabbitmq wrapper around node-amqp.
JavaScript
2
star
26

enquire

provides a simple convention based solution to overriding dependencies in node.js
JavaScript
2
star
27

dockerised-micro-service-node-js-architecture

This repo contains the source for A dockerised micro-service node.js architecture
JavaScript
2
star
28

gulp-tasks

JavaScript
2
star
29

azure-functions-express-openapi

JavaScript
2
star
30

grunt-elasticsearch-bulk

Grunt task for working with the elasticsearch bulk api
JavaScript
2
star
31

fastify-api-with-json-schema

Fastify, with json schema validation running of an external swagger file
JavaScript
2
star
32

grunt-newrelic

grunt-newrelic will generate a newrelic.js file and add it to the route of your project; with a license key and app_name pulled from a config file.
JavaScript
2
star
33

AndrewKeig

1
star
34

vision-web

JavaScript
1
star
35

appium-cuked

JavaScript
1
star
36

node-git-examples

Examples of using node git api
JavaScript
1
star
37

jedi.jasmine

sample project using the javascript jasmine testing library
JavaScript
1
star
38

grunt-cucumber-js

Grunt task for running Cucumber.js
JavaScript
1
star
39

maria

JavaScript
1
star
40

popcorn-apps-javascript-coding-standards

1
star
41

vision-api

JavaScript
1
star
42

lets-bounce

bouncing http requests with node.js and bouncy
JavaScript
1
star
43

ee

1
star
44

node.examples

misc node.js examples
JavaScript
1
star
45

azure-openapi

azure-openapi
JavaScript
1
star
46

boxhop

Example web application using node.js, express, mongoose, mongodb and socket.io which allows users to create and view multiple youtube queries
JavaScript
1
star
47

node-statsd-ns

JavaScript
1
star
48

bulk-mongodb

bulk insert data into mongdb for integration tests
JavaScript
1
star
49

azure-ad

JavaScript
1
star