joi-validate-middleware

Validate middleware generator using Joi

Usage no npm install needed!

<script type="module">
  import joiValidateMiddleware from 'https://cdn.skypack.dev/joi-validate-middleware';
</script>

README

Joi Validate Middleware

Validate middleware generator using Joi(^17.0.2)

Install

$ npm i joi-validate-middleware

Usage

const Joi = require('@hapi/joi');
const joiValidateMiddleware = require('joi-validate-middleware');

const schema = {
  params: Joi.object({
    id: Joi.number().required(),
  }).required(),
  body: Joi.object({
    content: Joi.string().required(),
  }).required()
};

/* or
const schema = {
  params: {
    id: Joi.number().required(),
  },
  body: {
    content: Joi.string().required(),
  }
};
*/

const validate = joiValidateMiddleware.create(schema);

const successRequest = {
  params: {
    id: 1,
  },
  body: {
    content: 'test',
  }
};

validate(successRequest);
console.log('success');

const errorRequest = {
  params: {
    id: 'other',
  },
};

try {
  validate(errorRequest);
  console.log('fail');
} catch (e) {
  console.log('success');
}