A validator middleware for koa. Inspired by express-validator.
The koa-req-validation requires validator, @koa/router and koa-bodyparser as peer dependencies.
Install peer dependencies
npm install validator@13 koa-bodyparser@4 @koa/router@10
Install koa-req-validation
npm install koa-req-validation
A basic usage example
import Router, { RouterContext } from "@koa/router";
import { query, validationResults } from "koa-req-validation";
// ...
const router = new Router();
router.get(
"/api/hello",
query("name")
.isLength({ min: 3, max: 20 })
.withMessage("The name has to be between 3 and 20 characters")
.build(), // <-- This is required at the end of each validation
async (ctx: RouterContext) => {
const result = validationResults(ctx);
if (result.hasErrors()) {
throw new RequestError(422, result.mapped());
}
const { name } = ctx.query;
ctx.body = `Hello ${name}`;
}
);
See the demo for other examples.
This module offers various validation and sanitation functions. Please note the following things:
ValidationResult.passedData()
output as wellValidationResult.passedData()
const result = validationResults(ctx);
if (result.hasErrors()) {
throw new RequestError(422, result.mapped());
}
const passed = result.passedData();
See the generated TypeDoc and ValidationChain for API documentation.
We use GitHub for issue tracking. Please look from previously submitted issues if someone else has already submitted the same issue.
Please see releases.
All contributions to the project are welcome.
Generated using TypeDoc