npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-validation

v4.1.1

Published

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

Downloads

231,595

Readme

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