You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
koa2-validation is a koa2 middleware to validate the request with Joi. Support body, params, query for Now.
Inspired by express-validation.
Version Tips
As new version Joi has some breaking changes, some old schema is not workable. To avoid the big change for using legacy koa2-validation version, you need to update your code as follows, if you want to use new version Joi.
// default
const validate = require('koa2-validation');
// with specific Joi
const joi = require("@hapi/joi");
const Validation = require("koa2-validation").Validation;
const validator = new Validation(joi);
const validate = validator.validate.bind(validator);
Please use the same Joi version when define your joi schema!!!
Usage
Install with npm:
npm i -S koa2-validation
Then, you can use koa2-valition to configure the validation schemas in routes. The example below is to
define three validations about user. file: test/lib/server.js
consthttp=require('http');constKoa=require('koa');constbodyParser=require('koa-bodyparser');constrouter=require('koa-router')();constvalidate=require('koa2-validation');// 1. import the koa2-validationconstuser=require('./user');router.post('/users',validate(user.v.addUser),user.addUser);// 3. setup the validate middlewarerouter.get('/users/:id',validate(user.v.getUserInfo),user.getUserInfo);router.get('/users',validate(user.v.getUserList),user.getUserList);constapp=newKoa();// error handlerapp.use(async(ctx,next)=>{try{awaitnext();}catch(err){ctx.status=err.status||err.code;ctx.body={success: false,message: err.message,};}});app.use(bodyParser());// bodyParser should be before the routersapp.use(router.routes());constserver=http.createServer(app.callback());module.exports=server;
You still need to define the validation schema in your controllers, as follows: file: test/lib/user.js
In the test foler, I made a demo about user management. You can get how to use koa2-validation from it.
If you have some questions, you can post an issue.
About
A koa2 middleware to validate the request with Joi