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

modern-express-joi

v1.0.7

Published

An express.js middleware makes a powerful validation request with the Joi validation.

Downloads

2

Readme

modern-express-joi

NPM version

An express.js middleware makes a powerful validation request with the Joi validation.

Inspiration

express-validator and Joi validation

Usage

  • npm install modern-express-joi
  • import modernValidator from 'modern-express-joi' or require('modern-express-joi').default
  • make an express middleware from passing schemas to modernValidator
  • add middleware to express
  • call req.checkAny for validating
  • call req.sanitizeAny for sanitizing

req.checkAny(String, [option])

Passing first params as string to select schema template. You can pass option as string for deep checking field by key name.

Here are available commands.

  • req.checkBody for validation req.body.
  • req.checkQuery for validation req.query.
  • req.checkParams for validation req.params.
  • ~~req.checkHeaders~~ coming soon
  • ~~req.checkCookies~~ coming soon

req.sanitizeAny(String)

This is similar to req.checkAny about passing params, but it converts the target object such as req.body, req.query, req.params etc to defining format in schemaTemplates.

modernValidator(Object, [option])

Passing schemaTemplates as object that has key name of your schema templates to construct an express middleware. The second optional parameter must be an object that contains functions, and key names are only errorFormatter, customValidator, or customSanitizer.

Example Passing Parameters

modernValidator(schemaTemplates, {
  errorFormatter: (errors) => {},
  customValidator: (value) => {},
  customSanitizer: (value) => {}
})

errorFormatter(errors)

A function that receives errors array or false for formatting errors when using req.validationErrors().

customValidator(value)

A function that validates the received value then returns error array or false.

customSanitizer(value, schema)

A function that recieves value and schema then returns formatting value follows by schema.

req.validationErrors()

Getting your result of validation after you called req.checkAny. It returns false if it has no validation errors, but It returns error array in otherwise.

Example Simple Validation

// examples/simple-validation.js
import modernValidator from 'modern-express-joi'
import Joi from 'joi'
import express from 'express'
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.json())

const template = Joi.object().keys({
  name: Joi.string().required(),
  age: Joi.number().positive().optional()
})
const schemaTemplates = {
  template
}

app.use(modernValidator(schemaTemplates))
app.post('/users', (req, res) => {
  req.checkBody('template')
  req.sanitizeBody('template')
  const errors = req.validationErrors()
  if (errors) res.status(400).send(errors)
  else res.status(200).send({ message: 'Success' })
})

app.listen(8080)
console.log('Running at port 8080')

Passed

// Request
{
  "name": "Hello",
  "age": 18
}

// Response 200
{ "message": "Success" }

Failed

// Request
{
  "age": "not number"
}

// Response 400
[
  {
    "message": "\"name\" is required",
    "path": "name",
    "type": "any.required",
    "context": {
      "key": "name"
    }
  }
]

Example Error Formatter

// examples/error-formatter.js
import modernValidator from 'modern-express-joi'
import Joi from 'joi'
import express from 'express'
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.json())

const template = Joi.object.keys({
  name: Joi.string().required(),
  age: Joi.number().positive().optional()
})
const schemaTemplates = {
  template
}
const errorFormatter = (errors) => (
  errors.map(error => error.message)
)

app.use(modernValidator(schemaTemplates, { errorFormatter }))
app.post('/users', (req, res) => {
  req.checkBody('template')
  req.sanitizeBody('template')
  const errors = req.validationErrors()
  if (errors) res.status(400).send(errors)
  else res.status(200).send({ message: 'Success' })
})

app.listen(8080)
console.log('Running at port 8080')

Example Deep Checking Field

// examples/deep-checking.js
import modernValidator from 'modern-express-joi'
import Joi from 'joi'
import express from 'express'
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.json())

const schemaTemplates = {
  templateName: Joi.string().required(),
  templateAge: Joi.number().positive().optional()
}

app.use(modernValidator(schemaTemplates))
app.post('/users', (req, res) => {
  req.checkBody('templateName', 'name')
  req.checkBody('templateAge', 'age')
  req.sanitizeBody('templateName', 'name')
  req.sanitizeBody('templateAge', 'age')
  const errors = req.validationErrors()
  if (errors) res.status(400).send(errors)
  else res.status(200).send({ message: 'Success' })
})

app.listen(8080)
console.log('Running at port 8080');