koa-request-validation
v1.1.4
Published
A simple, clean http requests validator for koajs application that is inspired by express validator and uses joi to make rules
Downloads
19
Maintainers
Readme
koa-request-validation
Object schema description language and validator for JavaScript objects.
Introduction
Looking for clean way to run validation against http request parameters, body, and query string is koajs?
Koa-request-validation uses joi schema to create rules that http requests can be validated against.
Installation
npm i koa-request-validation
Usage
const Koa = require('koa')
const validator = require('koa-request-validation')
let app = new Koa()
app.use(validator())
Example
In your controllers/route handlers
You can put these rules in a validation-rules folder and require them where need to clean up your controllers/request handlers
const Joi = require('joi');
const bodyRule = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email()
});
const paramsRule = Joi.object().keys({
id: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
}).required();
const queryRule = Joi.object().keys({
page: Joi.number().required(),
token: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required
}).required();
// Run validations.
ctx.validateBody(bodyRule)
ctx.validateParams(paramsRule)
ctx.validateQuery(queryRule)